package com.example.show_auto.utils

import com.example.show_auto.data.*
import com.example.show_auto.ui.pages.UltimateSkillsState


/**
 * 采集编队计算器
 * 专门用于计算菜地区的采集编队效率和推荐
 */
object CollectionTeamCalculator {
    
    // 存储最后计算的实验室地区总技法值（临时解决方案）
    private val lastLabAreaTotalSkills = mutableMapOf<String, Int>()
    
    /**
     * 获取实验室地区的最终总技法值
     */
    fun getLabAreaTotalSkill(skillType: String): Int {
        return lastLabAreaTotalSkills[skillType] ?: 0
    }
    
    /**
     * 更新实验室地区的总技法值缓存
     */
    fun updateLabAreaTotalSkill(skillType: String, totalSkillValue: Int) {
        lastLabAreaTotalSkills[skillType] = totalSkillValue
    }
    
    /**
     * 菜地区采集结果数据类
     */
    data class VegAreaResult(
        val chefName: String,           // 厨师名称
        val rarity: Int,                // 厨师星级
        val timeEfficiency: Int,        // 时间效率（秒）
        val owned: Boolean,             // 是否已拥有
        val area: String,               // 所属区域
        val collectionStats: CollectionStats  // 采集点统计
    )
    
    /**
     * 采集点统计数据类
     */
    data class CollectionStats(
        val meat: Int,          // 肉类采集点
        val fish: Int,          // 鱼类采集点
        val veg: Int,           // 蔬菜采集点
        val creation: Int       // 面类采集点
    )
    
    /**
     * 带统计数据的厨师
     */
    data class ChefWithStats(
        val chef: Chef,
        val stats: CollectionStats,
        val skillBonus: SkillBonus = SkillBonus(),
        val isUltimateTraining: Boolean = false // 是否已修炼
    ) {
        /**
         * 获取厨师的专长采集类型（最高的采集点类型）
         * 当多个采集点相等时，优先级：鱼 > 肉 > 菜 > 面
         */
        fun getSpecialty(): String {
            val max = maxOf(stats.meat, stats.fish, stats.veg, stats.creation)
            return when {
                stats.fish == max -> "鱼"
                stats.meat == max -> "肉" 
                stats.veg == max -> "菜"
                stats.creation == max -> "面"
                else -> "无"
            }
        }
        
        /**
         * 获取厨师相对于目标类型的专长采集类型
         * 当多个采集点相等且包含目标类型时，优先返回目标类型
         */
        fun getSpecialtyForTarget(targetType: String): String {
            val max = maxOf(stats.meat, stats.fish, stats.veg, stats.creation)
            
            // 获取所有等于最大值的采集类型
            val maxTypes = mutableListOf<String>()
            if (stats.meat == max) maxTypes.add("肉")
            if (stats.fish == max) maxTypes.add("鱼")
            if (stats.veg == max) maxTypes.add("菜")
            if (stats.creation == max) maxTypes.add("面")
            
            // 如果目标类型在最大值类型中，优先返回目标类型
            if (targetType in maxTypes) {
                return targetType
            }
            
            // 否则按照默认优先级返回
            return when {
                stats.fish == max -> "鱼"
                stats.meat == max -> "肉" 
                stats.veg == max -> "菜"
                stats.creation == max -> "面"
                else -> "无"
            }
        }
        
        /**
         * 获取指定类型的采集点数值
         */
        fun getCollectionValue(type: String): Int {
            return when (type) {
                "肉" -> stats.meat
                "鱼" -> stats.fish
                "菜" -> stats.veg
                "面" -> stats.creation
                else -> 0
            }
        }
        
        /**
         * 判断是否是需要保护的特殊厨师
         * 包括：1. 无技能的高星级厨师（4星、5星且无加成/暴击技能）
         *      2. 低星级高售价加成厨师（1-3星且售价加成≥30%）
         *      3. 稀有客人技能厨师（任何星级）
         * 这类厨师应该延后使用，只在采集点不达标时才考虑
         */
        fun isProtectedChef(): Boolean {
            val hasCollectionSkill = skillBonus.critMaterialBonus > 0 || skillBonus.gainBonus > 0
            val isHighRarityNoSkill = chef.rarity >= 4 && !hasCollectionSkill
            val isLowRarityHighPriceBonus = chef.rarity <= 3 && skillBonus.priceBonus >= 30
            val hasRareGuestSkill = skillBonus.hasRareGuestSkill
            
            return isHighRarityNoSkill || isLowRarityHighPriceBonus || hasRareGuestSkill
        }
        
        /**
         * 获取技能优先级分数（用于排序）
         * 返回 Pair<Int, Double>，第一个是优先级组别，第二个是组内排序分数
         * 新规则：暴击技能只有在已修炼时才有效，未修炼厨师的暴击技能无效
         */
        fun getSkillPriority(): Pair<Int, Double> {
            val totalCritMaterial = skillBonus.critMaterialBonus
            val totalCritChance = skillBonus.critChanceBonus
            val totalGainBonus = skillBonus.gainBonus
            
            // 判断是否有有效暴击技能：
            // 1. 必须有暴击技能 (totalCritMaterial > 0)
            // 2. 暴击概率必须>10%（修炼状态不影响这个判断）
            val hasEffectiveCrit = totalCritMaterial > 0 && totalCritChance > 10
            val hasGainSkill = totalGainBonus > 0
            
            return when {
                // 第一优先级：同时拥有有效暴击技能和加成技能
                hasEffectiveCrit && hasGainSkill -> {
                    // 按加成技能总和排序（因为要求对加成类技能进行排序）
                    val score = totalGainBonus * 1000.0 + totalCritMaterial
                    Pair(1, score)
                }
                // 第二优先级：只有有效暴击技能
                hasEffectiveCrit -> {
                    val score = totalCritMaterial * 1000.0 + totalCritChance
                    Pair(2, score)
                }
                // 第三优先级：只有加成技能
                hasGainSkill -> {
                    Pair(3, totalGainBonus.toDouble())
                }
                // 第四优先级：无有效技能
                else -> {
                    // 无效暴击技能也给一点分数，但优先级很低
                    val score = if (totalCritMaterial > 0) totalCritMaterial.toDouble() else 0.0
                    Pair(4, score)
                }
            }
        }
    }
    
    /**
     * 技能加成数据类
     */
    data class SkillBonus(
        val critMaterialBonus: Int = 0,    // 暴击素材百分比总和
        val critChanceBonus: Int = 0,      // 暴击概率百分比总和
        val gainBonus: Int = 0,            // 加成百分比总和
        val priceBonus: Int = 0,           // 售价加成百分比总和
        val hasRareGuestSkill: Boolean = false,  // 是否有稀有客人技能
        val hasOpeningTimeSkill: Boolean = false, // 是否含"开业时间/营业时间"等技能
        val openingTimePenalty: Int = 0,   // 开业时间减益百分比（负值）
        val rareGuestChanceBonus: Int = 0  // 稀有客人出现概率加成百分比
    )
    
    /**
     * 分离的技能加成数据类
     */
    data class SeparatedSkillBonus(
        val totalCritMaterial: Int = 0,       // 厨师技能+修炼技能+厨具技能的暴击素材（厨具暴击素材翻倍）
        val totalCritChance: Int = 0,         // 厨师技能+修炼技能+厨具技能的暴击率（厨具暴击率不翻倍）
        val totalMaterialGain: Int = 0        // 厨师技能+厨具技能的素材加成总和
    )
    
    /**
     * 计算菜地区采集编队结果
     * @param gameData 游戏数据
     * @param personalData 个人数据
     * @param vegEnabled 是否启用菜地区
     * @param vegAreaConfigs 菜地区配置列表
     * @return 菜地区采集结果列表
     */
    fun calculateVegAreaResults(
        gameData: GameData,
        personalData: PersonalData?,
        vegEnabled: Boolean,
        vegAreaConfigs: List<VegAreaItem> = emptyList(),
        useSilverShoes: Boolean = false
    ): List<VegAreaResult> {
        return calculateVegAreaResults(gameData, personalData, vegEnabled, vegAreaConfigs, useSilverShoes, false, false, false)
    }
    
    fun calculateVegAreaResults(
        gameData: GameData,
        personalData: PersonalData?,
        vegEnabled: Boolean,
        vegAreaConfigs: List<VegAreaItem> = emptyList(),
        useSilverShoes: Boolean = false,
        useMaxLevelAmber: Boolean = false,
        useAllUltimateTraining: Boolean = false,
        useAllChefs: Boolean = false
    ): List<VegAreaResult> {
        if (!vegEnabled) return emptyList()
        
        // 筛选厨师：根据useAllChefs参数决定是否使用所有厨师
        val ownedChefs = if (useAllChefs) {
            // 使用所有厨师
            gameData.chefs
        } else if (personalData != null) {
            // 只使用已拥有的厨师
            gameData.chefs.filter { chef ->
                personalData.chefs[chef.chefId]?.got == true
            }
        } else {
            // 没有个人数据时，显示所有厨师作为示例
            gameData.chefs.take(10) // 限制显示数量
        }
        
        // 计算所有厨师的最终采集点和技能加成（暂时不传目标类型，在分配时再计算）
        val chefsWithStats = ownedChefs.map { chef ->
            val stats = calculateChefCollectionStats(chef, gameData, personalData, useSilverShoes, useMaxLevelAmber, "", false, useAllUltimateTraining)
            val skillBonus = calculateChefSkillBonus(chef, gameData, personalData, "", useSilverShoes, useMaxLevelAmber, useAllUltimateTraining) // 不传目标类型，保持通用
            // 修炼状态：默认全修炼开启时为true，否则检查厨师是否已拥有且已修炼
            val isUltimateTraining = if (useAllUltimateTraining) {
                true
            } else {
                val personalChef = personalData?.chefs?.get(chef.chefId)
                personalChef?.got == true && personalChef.ult == true
            }
            
            val cws = ChefWithStats(chef, stats, skillBonus, isUltimateTraining)
            cws
        }
        
        // 智能分配厨师到各个地区
        val allocation = allocateChefsByArea(chefsWithStats, vegAreaConfigs, gameData, personalData, useSilverShoes, useMaxLevelAmber, useAllUltimateTraining)
        
        // 转换为VegAreaResult格式，按地区顺序返回，每个地区内按期望值降序排序
        return allocation.flatMap { (areaName, chefs) ->
            // 计算地区采集类型
            val areaType = when (areaName) {
                "池塘" -> "鱼"
                "牧场", "猪圈", "鸡舍" -> "肉"
                "菜棚", "菜地", "森林" -> "菜"
                "作坊" -> "面"
                else -> ""
            }
            
            // 按期望值降序排序每个地区内的厨师
            val sortedChefs = chefs.sortedByDescending { chefWithStats ->
                val separatedSkills = calculateSeparatedSkillBonus(chefWithStats.chef, gameData, personalData, areaType, useSilverShoes, useMaxLevelAmber, false, useAllUltimateTraining)
                separatedSkills.totalMaterialGain + (separatedSkills.totalCritChance / 100.0 * separatedSkills.totalCritMaterial)
            }
            
            sortedChefs.map { chefWithStats ->
                VegAreaResult(
                    chefName = chefWithStats.chef.name,
                    rarity = chefWithStats.chef.rarity,
                    timeEfficiency = 0, // 不再使用时间效率排序
                    owned = personalData?.chefs?.get(chefWithStats.chef.chefId)?.got ?: false,
                    area = areaName,
                    collectionStats = chefWithStats.stats
                )
            }
        }
    }
    
    // 存储无法满足采集点要求的地区
    private val insufficientAreas = mutableListOf<String>()
    
    /**
     * 智能分配厨师到各个地区
     */
    private fun allocateChefsByArea(
        chefsWithStats: List<ChefWithStats>,
        vegAreaConfigs: List<VegAreaItem>,
        gameData: GameData,
        personalData: PersonalData?,
        useSilverShoes: Boolean = false
    ): List<Pair<String, List<ChefWithStats>>> {
        return allocateChefsByArea(chefsWithStats, vegAreaConfigs, gameData, personalData, useSilverShoes, false, false)
    }
    
    private fun allocateChefsByArea(
        chefsWithStats: List<ChefWithStats>,
        vegAreaConfigs: List<VegAreaItem>,
        gameData: GameData,
        personalData: PersonalData?,
        useSilverShoes: Boolean = false,
        useMaxLevelAmber: Boolean = false,
        useAllUltimateTraining: Boolean = false
    ): List<Pair<String, List<ChefWithStats>>> {
        val allocation = mutableListOf<Pair<String, List<ChefWithStats>>>()
        val usedChefs = mutableSetOf<String>() // 记录已使用的厨师ID
        
        // 注意：不在此处清空insufficientAreas，由调用方统一管理
        
        // 过滤掉人数为0的地区，并按照配置顺序处理（严格遵循配置页顺序）
        val activeAreas = vegAreaConfigs.filter { it.currentPeople > 0 }
        
        for (area in activeAreas) {
            
            // 筛选适合该地区的厨师（未使用且有对应采集能力）
            val availableChefs = chefsWithStats.filter { c ->
                val notUsed = !usedChefs.contains(c.chef.chefId)
                val hasCap = c.getCollectionValue(area.type) > 0
                val noRare = !c.skillBonus.hasRareGuestSkill
                val noOpen = !c.skillBonus.hasOpeningTimeSkill
                val ok = notUsed && hasCap && noRare && noOpen
                ok
            }
            
            // 按分配策略排序厨师
            val sortedChefs = sortChefsByAllocationStrategy(availableChefs, area.type, gameData, personalData)
            

            
            // 使用智能分配算法
            val allocatedChefs = allocateChefsByBalance(
                sortedChefs, 
                area.currentPeople, 
                area.currentCapacity, 
                area.type,
                area.name,
                gameData,
                personalData
            )
            
            // 应用全场采集点加成
            val enhancedChefs = applyGlobalCollectionBonus(allocatedChefs, gameData, personalData, useAllUltimateTraining)
            
            // 检查是否满足采集点要求（使用加成后的数值）
            val totalCapacity = enhancedChefs.sumOf { it.getCollectionValue(area.type) }
            if (totalCapacity < area.currentCapacity && enhancedChefs.size == area.currentPeople) {
                // 无法满足采集点要求，记录该地区
                insufficientAreas.add("${area.name}(需要${area.currentCapacity}采集点，实际${totalCapacity})")
            }
            
            // 只为菜地区打印详细的最终分配结果
            if (area.name == "菜地") {
                println("--- ${area.name} 最终分配结果 ---")
                println("分配人数: ${enhancedChefs.size}/${area.currentPeople}, 总采集点: ${totalCapacity}/${area.currentCapacity}")
                if (totalCapacity < area.currentCapacity) {
                    println("⚠️ 采集点不足: 缺少${area.currentCapacity - totalCapacity}点")
                } else {
                    println("✅ 采集点满足要求")
                }
                
                enhancedChefs.forEachIndexed { index, chef ->
                    val targetSpecificSkillBonus = calculateChefSkillBonus(chef.chef, gameData, personalData, area.type, useSilverShoes, useMaxLevelAmber)
                    val expectationValue = targetSpecificSkillBonus.gainBonus + (targetSpecificSkillBonus.critChanceBonus / 100.0 * targetSpecificSkillBonus.critMaterialBonus)
                    val collectionValue = chef.getCollectionValue(area.type)
                    
                    println("${index + 1}. ${chef.chef.name}: 采集点${collectionValue}, 期望值${String.format("%.1f", expectationValue)}")
                }
                println("---------------------------")
            } else {
                // 其他地区只打印简要信息
                println("${area.name}: ${enhancedChefs.size}人, 采集点${totalCapacity}/${area.currentCapacity}")
            }
            
            // 记录已使用的厨师
            enhancedChefs.forEach { chef ->
                usedChefs.add(chef.chef.chefId)
            }
            
            allocation.add(area.name to enhancedChefs)
        }
        
        return allocation
    }
    
    /**
     * 获取无法满足采集点要求的地区列表
     */
    fun getInsufficientAreas(): List<String> {
        return insufficientAreas.toList()
    }
    
    /**
     * 清空无法满足采集点要求的地区列表
     * 应该在开始新的一键查询前调用
     */
    fun clearInsufficientAreas() {
        insufficientAreas.clear()
    }
    
    /**
     * 应用全场采集点加成到菜地区厨师
     * 检查每个厨师是否有"场上所有厨师*和*各+*"类技能，如果有则给所有厨师（包括自己）加成
     */
    private fun applyGlobalCollectionBonus(
        allocatedChefs: List<ChefWithStats>,
        gameData: GameData,
        personalData: PersonalData? = null,
        useAllUltimateTraining: Boolean = false
    ): List<ChefWithStats> {
        if (allocatedChefs.isEmpty()) return allocatedChefs
        
        val enhancedChefs = allocatedChefs.toMutableList()
        
        // 遍历每个厨师，检查是否有全场加成技能
        for (i in enhancedChefs.indices) {
            val chef = enhancedChefs[i]
            val globalBonusInfo = calculateGlobalBonusValues(chef.chef, gameData, personalData, useAllUltimateTraining)
            
            if (globalBonusInfo.hasBonus()) {
                // 该厨师有全场加成技能，给所有厨师（包括自己）应用加成
                for (j in enhancedChefs.indices) {
                    val targetChef = enhancedChefs[j]
                    val enhancedStats = applyGlobalBonusToStats(targetChef.stats, globalBonusInfo)
                    enhancedChefs[j] = targetChef.copy(stats = enhancedStats)
                }
            }
        }
        
        return enhancedChefs
    }
    
    /**
     * 将全场加成应用到采集点统计
     */
    private fun applyGlobalBonusToStats(
        stats: CollectionStats,
        globalBonus: GlobalBonusInfo
    ): CollectionStats {
        return CollectionStats(
            meat = stats.meat + globalBonus.meatBonus,
            fish = stats.fish + globalBonus.fishBonus,
            veg = stats.veg + globalBonus.vegBonus,
            creation = stats.creation + globalBonus.creationBonus
        )
    }
    
    /**
     * 应用全场采集点加成到玉片区厨师
     * 检查每个厨师是否有"场上所有厨师*和*各+*"类技能，如果有则给所有厨师（包括自己）加成
     */
    private fun applyGlobalCollectionBonusToJadeArea(
        allocatedChefs: List<ChefWithStats>,
        gameData: GameData,
        personalData: PersonalData? = null,
        useAllUltimateTraining: Boolean = false
    ): List<ChefWithStats> {
        if (allocatedChefs.isEmpty()) return allocatedChefs
        
        val enhancedChefs = allocatedChefs.toMutableList()
        
        // 遍历每个厨师，检查是否有全场加成技能
        for (i in enhancedChefs.indices) {
            val chef = enhancedChefs[i]
            val globalBonusInfo = calculateGlobalBonusValues(chef.chef, gameData, personalData, useAllUltimateTraining)
            
            if (globalBonusInfo.hasBonus()) {
                // 该厨师有全场加成技能，给所有厨师（包括自己）应用加成
                for (j in enhancedChefs.indices) {
                    val targetChef = enhancedChefs[j]
                    val enhancedStats = applyGlobalBonusToStats(targetChef.stats, globalBonusInfo)
                    enhancedChefs[j] = targetChef.copy(stats = enhancedStats)
                }
            }
            // 注意：这里不需要break，因为可能有多个厨师都有全场加成技能
        }
        
        return enhancedChefs
    }
    
    /**
     * 按分配策略排序厨师
     * 优先级：专长匹配 > 修炼状态（已修炼或加成技能优先）> 素材获取技能优先级 > 采集点高
     */
    private fun sortChefsByAllocationStrategy(
        chefs: List<ChefWithStats>,
        targetType: String,
        gameData: GameData,
        personalData: PersonalData?
    ): List<ChefWithStats> {
        val base = compareBy<ChefWithStats> { chef -> if (chef.isProtectedChef()) 1 else 0 }
        
        // 为当前目标类型重新计算技能加成（包含心法盘加成）
        val chefsWithTargetSkills = chefs.map { chefWithStats ->
            val targetSpecificSkillBonus = calculateChefSkillBonus(
                chefWithStats.chef, gameData, personalData, targetType
            )
            chefWithStats.copy(skillBonus = targetSpecificSkillBonus)
        }
        
        // 统一排序逻辑：不再区分鱼类和其他区域
        val sortedChefs = chefsWithTargetSkills.sortedWith(
            base
                .thenByDescending { chef -> 
                    // 主要排序：智能技能评分
                    calculateSmartSkillScore(chef.skillBonus)
                }
                .thenByDescending { chef -> 
                    // 次级排序1：素材加成（分数相同时，素材加成高的优先）
                    chef.skillBonus.gainBonus
                }
                .thenByDescending { chef -> 
                    // 次级排序2：暴击率 × 暴击素材（素材加成相同时，暴击收益高的优先）
                    (chef.skillBonus.critChanceBonus / 100.0) * chef.skillBonus.critMaterialBonus
                }
                .thenByDescending { chef -> 
                    // 次级排序3：专长匹配度
                    if (chef.getSpecialtyForTarget(targetType) == targetType) 1 else 0
                }
                .thenByDescending { chef -> 
                    // 次级排序4：绿色心法盘数量 + 采集点数值
                    getGreenAmberCount(chef.chef) * 10 + chef.getCollectionValue(targetType)
                }
                .thenBy { chef ->
                    // 次级排序5：采集点平衡性（避免浪费）
                    val total = chef.stats.meat + chef.stats.fish + chef.stats.veg + chef.stats.creation
                    val targetValue = chef.getCollectionValue(targetType)
                    total - targetValue
                }
        )
        
        return sortedChefs
    }
    
    /**
     * 获取厨师的绿色心法盘数量（从diskDesc获取）
     */
    private fun getGreenAmberCount(chef: Chef): Int {
        val diskDesc = chef.diskDesc
        if (diskDesc.isEmpty()) return 0
        
        // 解析类似 "蓝|绿|绿<br>最高5级" 的格式
        val diskTypes = diskDesc.split("<br>")[0] // 取第一部分，去掉等级描述
        val types = diskTypes.split("|") // 分割每个颜色
        
        return types.count { it.trim() == "绿" } // 统计绿色数量
    }
    
    /**
     * 智能分配算法：先按技能分配满人数，再智能替换以满足采集点要求
     */
    private fun allocateChefsByBalance(
        sortedChefs: List<ChefWithStats>,
        neededCount: Int,
        targetCapacity: Int,
        targetType: String,
        areaName: String = "",
        gameData: GameData,
        personalData: PersonalData?
    ): List<ChefWithStats> {
        if (sortedChefs.isEmpty()) return emptyList()
        
        val result = mutableListOf<ChefWithStats>()
        val availableChefs = sortedChefs.toMutableList()
        
        // 第一阶段：按技能优先级直接分配到满足人数需求
        val isDetailedLogging = areaName == "菜地"
        if (isDetailedLogging) {
            println("🔄 第一阶段：按技能优先级分配厨师")
        }
        
        while (result.size < neededCount && availableChefs.isNotEmpty()) {
            val chef = availableChefs.removeAt(0)
            // 保护：稀有客人/开业时间技能厨师永不使用
            if (chef.skillBonus.hasRareGuestSkill || chef.skillBonus.hasOpeningTimeSkill) {
                if (isDetailedLogging) {
                    println("   跳过 ${chef.chef.name}: 有稀有客人或开业时间技能")
                }
                continue
            }
            result.add(chef)
            if (isDetailedLogging) {
                println("   选择 ${chef.chef.name}: 采集点${chef.getCollectionValue(targetType)}")
            }
        }
        
        // 第二阶段：检查采集点是否满足要求，如果不满足则进行智能替换
        var currentCapacity = result.sumOf { it.getCollectionValue(targetType) }
        println("第一阶段完成: 当前采集点${currentCapacity}/${targetCapacity}")
        
        if (currentCapacity < targetCapacity && availableChefs.isNotEmpty()) {
            println("🔧 第二阶段：智能替换优化（需要增加${targetCapacity - currentCapacity}采集点）")
            
            // 新的替换策略：按期望值排序，只考虑替换期望值最低的后三名厨师
            val sortedTeam = result.sortedByDescending { chef -> 
                val skillBonus = calculateChefSkillBonus(chef.chef, gameData, personalData, targetType)
                skillBonus.gainBonus + (skillBonus.critChanceBonus / 100.0 * skillBonus.critMaterialBonus)
            }
            
            // 只考虑替换期望值最低的后三名厨师，保护期望值最高的前两名
            val candidatesForReplacement = if (sortedTeam.size >= 3) {
                sortedTeam.takeLast(3) // 期望值最低的后三名
            } else {
                sortedTeam.drop(maxOf(0, 2)) // 如果总数不足3，至少保护前两名高期望值厨师
            }
            
            var replacementMade = false
            
            // 逐个检查后三名厨师是否能被替换以达到采集点要求
            for (candidateChef in candidatesForReplacement) {
                if (currentCapacity >= targetCapacity) break // 已经达标，停止替换
                
                val currentChefCapacity = candidateChef.getCollectionValue(targetType)
                val currentChefSkillBonus = calculateChefSkillBonus(candidateChef.chef, gameData, personalData, targetType)
                val currentChefExpectation = currentChefSkillBonus.gainBonus + (currentChefSkillBonus.critChanceBonus / 100.0 * currentChefSkillBonus.critMaterialBonus)
                
                // 计算替换该厨师后需要的最小采集点增量
                val neededGap = targetCapacity - (currentCapacity - currentChefCapacity)
                
                if (isDetailedLogging) {
                    println("   检查替换: ${candidateChef.chef.name}(期望值${String.format("%.1f", currentChefExpectation)}, 采集点${currentChefCapacity}) -> 需要增加${neededGap}采集点")
                }
                
                // 找到所有能满足采集点要求的替换厨师
                val qualifiedReplacements = availableChefs.filter { replacement ->
                    val replacementCapacity = replacement.getCollectionValue(targetType)
                    val topTwoSum = getTopTwoCollectionSum(replacement)
                    replacementCapacity >= neededGap && topTwoSum <= 25 // 关键：满足采集点增量且两个最高采集点之和不超过25
                }
                
                if (qualifiedReplacements.isEmpty()) {
                    if (isDetailedLogging) {
                        // 检查是否有能补充采集点但被两个最高采集点过滤的厨师
                        val capacityQualified = availableChefs.filter { replacement ->
                            replacement.getCollectionValue(targetType) >= neededGap
                        }
                        val filteredByTopTwo = capacityQualified.filter { replacement ->
                            getTopTwoCollectionSum(replacement) > 25
                        }
                        
                        if (filteredByTopTwo.isNotEmpty()) {
                            println("   ❌ ${filteredByTopTwo.size}个厨师能补充${neededGap}采集点但两个最高采集点之和>25，已过滤")
                            filteredByTopTwo.forEach { chef ->
                                val topTwoSum = getTopTwoCollectionSum(chef)
                                println("      过滤: ${chef.chef.name}(采集点${chef.getCollectionValue(targetType)}, 两个最高之和${topTwoSum})")
                            }
                        }
                        println("   ❌ 没有符合条件的厨师能替换 ${candidateChef.chef.name}")
                    }
                    continue
                }
                
                if (isDetailedLogging) {
                    println("   找到${qualifiedReplacements.size}个符合条件的替换厨师(采集点≥${neededGap}且两个最高采集点之和≤25)")
                }
                
                // 在满足采集点要求的厨师中，选择期望值最高的
                val bestReplacement = qualifiedReplacements.maxByOrNull { replacement ->
                    val replacementSkillBonus = calculateChefSkillBonus(replacement.chef, gameData, personalData, targetType)
                    replacementSkillBonus.gainBonus + (replacementSkillBonus.critChanceBonus / 100.0 * replacementSkillBonus.critMaterialBonus)
                }
                
                if (bestReplacement != null) {
                    val replacementCapacity = bestReplacement.getCollectionValue(targetType)
                    val replacementSkillBonus = calculateChefSkillBonus(bestReplacement.chef, gameData, personalData, targetType)
                    val replacementExpectation = replacementSkillBonus.gainBonus + (replacementSkillBonus.critChanceBonus / 100.0 * replacementSkillBonus.critMaterialBonus)
                    val capacityGain = replacementCapacity - currentChefCapacity
                    val expectationGain = replacementExpectation - currentChefExpectation
                    
                    // 进行替换
                    result.remove(candidateChef)
                    result.add(bestReplacement)
                    availableChefs.remove(bestReplacement)
                    availableChefs.add(candidateChef)
                    
                    // 更新当前采集点
                    currentCapacity = currentCapacity - currentChefCapacity + replacementCapacity
                    replacementMade = true
                    
                    if (isDetailedLogging) {
                        println("   ✅ 替换成功: ${candidateChef.chef.name} -> ${bestReplacement.chef.name}")
                        println("       期望值: ${String.format("%.1f", currentChefExpectation)} -> ${String.format("%.1f", replacementExpectation)} (+${String.format("%.1f", expectationGain)})")
                        println("       采集点: ${currentChefCapacity} -> ${replacementCapacity} (+${capacityGain}), 当前总计${currentCapacity}")
                        if (currentCapacity >= targetCapacity) {
                            println("   🎯 采集点已达标！")
                        }
                    }
                    
                    // 找到一个有效替换后，停止当前轮次，重新评估（因为队伍构成已改变）
                    break
                } else {
                    if (isDetailedLogging) {
                        println("   ❌ 未找到符合条件的替换厨师")
                    }
                }
            }
            
                         if (!replacementMade && isDetailedLogging) {
                 println("   🔒 后三名厨师都无法找到合适的替换")
             }
             
             // 第二轮替换：如果第一轮无法达标，按采集点最低优先进行替换
             if (currentCapacity < targetCapacity && availableChefs.isNotEmpty()) {
                 if (isDetailedLogging) {
                     println("🔄 第三阶段：按采集点最低优先替换（仍需增加${targetCapacity - currentCapacity}采集点）")
                 }
                 
                 var secondRoundReplacementMade = true
                 while (currentCapacity < targetCapacity && secondRoundReplacementMade && availableChefs.isNotEmpty()) {
                     secondRoundReplacementMade = false
                     
                     // 找到当前队伍中采集点最低的厨师，采集点相同时优先选择期望值最低的
                     val lowestCapacityChef = result.minWithOrNull(compareBy<ChefWithStats> { chef ->
                         chef.getCollectionValue(targetType)
                     }.thenBy { chef -> 
                         val skillBonus = calculateChefSkillBonus(chef.chef, gameData, personalData, targetType)
                         skillBonus.gainBonus + (skillBonus.critChanceBonus / 100.0 * skillBonus.critMaterialBonus)
                     })
                     
                     if (lowestCapacityChef == null) break
                     
                     val currentChefCapacity = lowestCapacityChef.getCollectionValue(targetType)
                     val currentChefSkillBonus = calculateChefSkillBonus(lowestCapacityChef.chef, gameData, personalData, targetType)
                     val currentChefExpectation = currentChefSkillBonus.gainBonus + (currentChefSkillBonus.critChanceBonus / 100.0 * currentChefSkillBonus.critMaterialBonus)
                     
                     // 当前还需要的采集点数
                     val stillNeeded = targetCapacity - currentCapacity
                     
                     if (isDetailedLogging) {
                         println("   检查替换: ${lowestCapacityChef.chef.name}(期望值${String.format("%.1f", currentChefExpectation)}, 采集点${currentChefCapacity}) -> 当前还差${stillNeeded}采集点")
                     }
                     
                     // 寻找能够改善的替换厨师：采集点必须大于当前厨师且两个最高采集点之和不超过25
                     val potentialReplacements = availableChefs.filter { replacement ->
                         val topTwoSum = getTopTwoCollectionSum(replacement)
                         replacement.getCollectionValue(targetType) > currentChefCapacity && topTwoSum <= 25
                     }
                     
                     if (potentialReplacements.isEmpty()) {
                         if (isDetailedLogging) {
                             // 检查是否有采集点更高但被两个最高采集点过滤的厨师
                             val capacityHigher = availableChefs.filter { replacement ->
                                 replacement.getCollectionValue(targetType) > currentChefCapacity
                             }
                             val filteredByTopTwo = capacityHigher.filter { replacement ->
                                 getTopTwoCollectionSum(replacement) > 25
                             }
                             
                             if (filteredByTopTwo.isNotEmpty()) {
                                 println("   ❌ ${filteredByTopTwo.size}个厨师采集点更高但两个最高采集点之和>25，已过滤")
                                 filteredByTopTwo.forEach { chef ->
                                     val topTwoSum = getTopTwoCollectionSum(chef)
                                     println("      过滤: ${chef.chef.name}(采集点${chef.getCollectionValue(targetType)}, 两个最高之和${topTwoSum})")
                                 }
                             } else {
                                 println("   ❌ 没有采集点更高的厨师可以替换")
                             }
                         }
                         break
                     }
                     
                     // 优先寻找能够刚好补足或接近补足缺口的厨师
                     val idealCapacity = currentChefCapacity + stillNeeded
                     val bestReplacement = potentialReplacements.minByOrNull { replacement ->
                         val replacementCapacity = replacement.getCollectionValue(targetType)
                         // 计算与理想采集点的距离，越接近越好
                         kotlin.math.abs(replacementCapacity - idealCapacity)
                     }
                     
                     if (bestReplacement != null) {
                         val replacementCapacity = bestReplacement.getCollectionValue(targetType)
                         val replacementSkillBonus = calculateChefSkillBonus(bestReplacement.chef, gameData, personalData, targetType)
                         val replacementExpectation = replacementSkillBonus.gainBonus + (replacementSkillBonus.critChanceBonus / 100.0 * replacementSkillBonus.critMaterialBonus)
                         val capacityGain = replacementCapacity - currentChefCapacity
                         val expectationGain = replacementExpectation - currentChefExpectation
                         
                         // 进行替换
                         result.remove(lowestCapacityChef)
                         result.add(bestReplacement)
                         availableChefs.remove(bestReplacement)
                         availableChefs.add(lowestCapacityChef)
                         
                         // 更新当前采集点
                         currentCapacity = currentCapacity - currentChefCapacity + replacementCapacity
                         secondRoundReplacementMade = true
                         
                         if (isDetailedLogging) {
                             println("   ✅ 替换成功: ${lowestCapacityChef.chef.name} -> ${bestReplacement.chef.name}")
                             println("       期望值: ${String.format("%.1f", currentChefExpectation)} -> ${String.format("%.1f", replacementExpectation)} (+${String.format("%.1f", expectationGain)})")
                             println("       采集点: ${currentChefCapacity} -> ${replacementCapacity} (+${capacityGain}), 当前总计${currentCapacity}")
                             if (currentCapacity >= targetCapacity) {
                                 println("   🎯 采集点已达标！")
                             }
                         }
                     } else {
                         if (isDetailedLogging) {
                             println("   ❌ 没有可用的替换厨师，无法继续优化")
                         }
                         break
                     }
                 }
                 
                 if (isDetailedLogging) {
                     println("第三阶段完成: 最终采集点${currentCapacity}/${targetCapacity}")
                 }
             }
            if (isDetailedLogging) {
                println("第二阶段完成: 最终采集点${currentCapacity}/${targetCapacity}")
            }
        } else {
            if (isDetailedLogging) {
                println("✅ 第一阶段已满足采集点要求，无需优化")
            }
        }
        
        if (isDetailedLogging) {
            println("🎯 智能分配完成: 分配${result.size}名厨师，总采集点${result.sumOf { it.getCollectionValue(targetType) }}")
        }
        
        return result
    }
    
    /**
     * 寻找最佳替换厨师（新策略）
     * 逻辑：
     * 1. 在能满足采集点要求的厨师中，选择技能评分最高的
     * 2. 如果没有能满足要求的厨师，选择采集点最高且技能评分最高的
     */
    private fun findBestReplacementChefBySkill(
        candidateChefs: List<ChefWithStats>,
        neededGap: Int,
        targetType: String
    ): ChefWithStats? {
        if (candidateChefs.isEmpty()) return null
        
        // 筛选能够达到采集点要求的厨师
        val sufficientChefs = candidateChefs.filter { chef ->
            chef.getCollectionValue(targetType) >= neededGap
        }
        
        return if (sufficientChefs.isNotEmpty()) {
            // 有能达到要求的厨师，选择技能评分最高的
            sufficientChefs.maxByOrNull { chef ->
                calculateSkillScore(chef)
            }
        } else {
            // 没有能达到要求的厨师，按采集点分组，选择采集点最高且技能评分最高的
            val maxCapacity = candidateChefs.maxOf { it.getCollectionValue(targetType) }
            val highestCapacityChefs = candidateChefs.filter { 
                it.getCollectionValue(targetType) == maxCapacity 
            }
            highestCapacityChefs.maxByOrNull { chef ->
                calculateSkillScore(chef)
            }
        }
    }
    
    /**
     * 计算厨师的技能评分（用于替换功能）
     */
    private fun calculateSkillScore(chef: ChefWithStats): Double {
        return calculateSmartSkillScore(chef.skillBonus)
    }
    
    /**
     * 智能技能评分系统
     * 考虑技能类型的实际价值，而不是简单数值相加
     * 新规则：暴击率>30%的厨师也进入最高优先级，按暴击素材、暴击率、素材量排序
     */
    private fun calculateSmartSkillScore(skillBonus: SkillBonus): Double {
        val gainBonus = skillBonus.gainBonus
        val critMaterialBonus = skillBonus.critMaterialBonus
        val critChanceBonus = skillBonus.critChanceBonus
        
        // 检查是否有任何技能
        val hasAnySkill = gainBonus > 0 || critMaterialBonus > 0 || critChanceBonus > 0
        
        if (!hasAnySkill) {
            // 无技能的厨师优先级最低
            return 0.0
        }
        
        // 将暴击率从百分比转换为小数（如：30% -> 0.3）
        val critChanceDecimal = critChanceBonus / 100.0
        
        // 计算公式：素材加成 + 暴击率 × 暴击素材
        val score = gainBonus + (critChanceDecimal * critMaterialBonus)
        
        return score
    }
    
    /**
     * 计算厨师的最终采集点数据（包含装备加成）
     */
    fun calculateChefCollectionStats(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?
    ): CollectionStats {
        return calculateChefCollectionStats(chef, gameData, personalData, false, false, "", false, false)
    }
    
    /**
     * 计算厨师的采集点数据（厨师基础数据+技能加成+厨具加成+心法盘加成）
     * @param useSilverShoes 是否使用银布鞋逻辑（菜地区专用）
     */
    fun calculateChefCollectionStats(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        useSilverShoes: Boolean = false
    ): CollectionStats {
        return calculateChefCollectionStats(chef, gameData, personalData, useSilverShoes, false, "", false, false)
    }
    
    fun calculateChefCollectionStats(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        useSilverShoes: Boolean = false,
        useMaxLevelAmber: Boolean = false,
        targetType: String = "",
        isJadeArea: Boolean = false,
        useAllUltimateTraining: Boolean = false
    ): CollectionStats {
        var meat = chef.meat
        var fish = chef.fish
        var veg = chef.veg
        var creation = chef.creation
        
        // 1) 解析厨师技能采集加成和素材获得加成
        if (chef.skill != 0) {
            val skill = gameData.skills.find { it.skillId == chef.skill }
            if (skill != null) {
                val skillDesc = skill.desc
                val bonusAmount = extractBonusAmount(skillDesc)
                when {
                    skillDesc.contains("肉类采集") || skillDesc.contains("采集肉类") || skillDesc.contains("Meat") -> meat += bonusAmount
                    skillDesc.contains("水产采集") || skillDesc.contains("鱼类采集") || skillDesc.contains("采集鱼类") || skillDesc.contains("Fish") -> fish += bonusAmount
                    skillDesc.contains("蔬菜采集") || skillDesc.contains("采集蔬菜") || skillDesc.contains("Vegetable") -> veg += bonusAmount
                    skillDesc.contains("面类采集") || skillDesc.contains("采集面类") || skillDesc.contains("Creation") -> creation += bonusAmount
                    skillDesc.contains("全采集") -> { meat += bonusAmount; fish += bonusAmount; veg += bonusAmount; creation += bonusAmount }
                }
                
                // 解析素材获得加成（如"素材获得+20%"）
                val materialGainPattern = Regex("素材获得\\+(\\d+)%")
                val materialGainMatch = materialGainPattern.find(skillDesc)
                if (materialGainMatch != null) {
                    // 这里可以记录素材获得加成，但不影响采集点计算
            
                }
            }
        }
        
        // 2) 解析厨师修炼技能采集加成和素材获得加成
        // 检查是否应该应用修炼技能
        val shouldApplyUltimateSkills = if (useAllUltimateTraining) {
            true
        } else {
            val personalChef = personalData?.chefs?.get(chef.chefId)
            personalChef?.got == true && personalChef.ult == true
        }
        
        if (chef.hasUltimateSkill() && shouldApplyUltimateSkills) {
            chef.getAllUltimateSkills().forEach { skillId ->
                val skill = gameData.skills.find { it.skillId == skillId }
                if (skill != null) {
                    val skillDesc = skill.desc
                    val bonusAmount = extractBonusAmount(skillDesc)
                    when {
                        skillDesc.contains("肉类采集") || skillDesc.contains("采集肉类") || skillDesc.contains("Meat") -> meat += bonusAmount
                        skillDesc.contains("水产采集") || skillDesc.contains("鱼类采集") || skillDesc.contains("采集鱼类") || skillDesc.contains("Fish") -> fish += bonusAmount
                        skillDesc.contains("蔬菜采集") || skillDesc.contains("采集蔬菜") || skillDesc.contains("Vegetable") -> veg += bonusAmount
                        skillDesc.contains("面类采集") || skillDesc.contains("采集面类") || skillDesc.contains("Creation") -> creation += bonusAmount
                        skillDesc.contains("全采集") -> { meat += bonusAmount; fish += bonusAmount; veg += bonusAmount; creation += bonusAmount }
                    }
                    
                    // 解析素材获得加成（如"素材获得+20%"）
                    val materialGainPattern = Regex("素材获得\\+(\\d+)%")
                    val materialGainMatch = materialGainPattern.find(skillDesc)
                    if (materialGainMatch != null) {
                        // 这里可以记录素材获得加成，但不影响采集点计算
                
                    }
                }
            }
        }
        
        // 3) 解析厨具采集加成
        val equipId = personalData?.chefs?.get(chef.chefId)?.equip
        
        // 银布鞋逻辑：如果开启了银布鞋开关
        val finalEquipId = if (useSilverShoes) {
            if (equipId != null) {
                // 检查厨师当前装备是否为指定厨具ID
                val allowedEquipIds = listOf(1088, 76, 77, 78, 64, 841)
                if (equipId in allowedEquipIds) {
                    equipId // 使用当前装备
                } else {
                    65 // 默认使用65号厨具（银布鞋）
                }
            } else {
                65 // 没有装备时默认使用65号厨具（银布鞋）
            }
        } else {
            equipId // 使用原有逻辑
        }
        
        if (finalEquipId != null) {
            val equip = gameData.equips.find { it.equipId == finalEquipId.toString() }
            if (equip != null) {
                val bonus = parseEquipCollectionBonus(equip, gameData.skills)
                // 修炼528翻倍
                val multiplier = if (chef.getAllUltimateSkills().any { it == 528 }) 2 else 1
                meat += bonus.meat * multiplier
                fish += bonus.fish * multiplier
                veg += bonus.veg * multiplier
                creation += bonus.creation * multiplier
            }
        }
        
        // 4) 解析绿色心法盘（遗玉）采集加成
        run {
            if (useMaxLevelAmber && isJadeArea) {
                // 玉片区满级心法盘逻辑：只影响采集点加成，不影响素材加成
                if (targetType.isNotEmpty()) {
                    // 只为当前地区对应的采集类型计算满级心法盘采集点加成
                    val bonus = calculateJadeMaxLevelAmberBonus(chef, gameData, targetType)
                    when (targetType) {
                        "肉" -> meat += bonus
                        "鱼" -> fish += bonus
                        "菜" -> veg += bonus
                        "面" -> creation += bonus
                    }
                }
            } else if (useMaxLevelAmber && !isJadeArea) {
                // 菜地区满级心法盘逻辑：只影响素材加成，不影响采集点
                // 因此在采集点计算中跳过满级心法盘逻辑，采集点加成交由实际装备的心法盘处理
                
                // 使用厨师实际装备的心法盘计算采集点
                val pChef = personalData?.chefs?.get(chef.chefId)
                val diskLevel = (pChef?.dlv ?: 1).coerceAtLeast(1)
                val amberIds = pChef?.ambers ?: emptyList()
                if (amberIds.isNotEmpty()) {
                    amberIds.forEach { aid ->
                        if (aid == 0) return@forEach
                        val amber = gameData.ambers.find { it.amberId == aid.toString() }
                        if (amber != null && amber.type == 2) { // 绿盘
                            val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                            // 按每个skill逐一识别类型并加成（仅处理采集点加成，不处理素材获得加成）
                            amber.skill.forEach { sid ->
                                val skillObj = gameData.skills.find { it.skillId == sid }
                                if (skillObj != null) {
                                    val sDesc = skillObj.desc
                                    
                                    // 只处理采集点加成类技能，跳过素材获得类技能
                                    if (sDesc.contains("采集获得") || sDesc.contains("食材+")) {
                                        // 这是素材获得类技能，不影响采集点，跳过
                                        return@forEach
                                    }
                                    
                                    val base = extractBonusAmount(skillObj.desc)
                                    val totalAdd = base + levelBonusEach
                                    when {
                                        sDesc.contains("肉类采集") || sDesc.contains("采集肉类") || sDesc.contains("Meat") -> meat += totalAdd
                                        sDesc.contains("水产采集") || sDesc.contains("鱼类采集") || sDesc.contains("采集鱼类") || sDesc.contains("Fish") -> fish += totalAdd
                                        sDesc.contains("蔬菜采集") || sDesc.contains("采集蔬菜") || sDesc.contains("Vegetable") -> veg += totalAdd
                                        sDesc.contains("面类采集") || sDesc.contains("采集面类") || sDesc.contains("Creation") -> creation += totalAdd
                                        sDesc.contains("全采集") -> { meat += totalAdd; fish += totalAdd; veg += totalAdd; creation += totalAdd }
                                        else -> {
                                            // 若skill无法判定类型，则尝试用amber.desc作为兜底
                                            val aDesc = amber.desc
                                            when {
                                                aDesc.contains("肉类采集") || aDesc.contains("采集肉类") || aDesc.contains("Meat") -> meat += totalAdd
                                                aDesc.contains("水产采集") || aDesc.contains("鱼类采集") || aDesc.contains("采集鱼类") || aDesc.contains("Fish") -> fish += totalAdd
                                                aDesc.contains("蔬菜采集") || aDesc.contains("采集蔬菜") || aDesc.contains("Vegetable") -> veg += totalAdd
                                                aDesc.contains("面类采集") || aDesc.contains("采集面类") || aDesc.contains("Creation") -> creation += totalAdd
                                                aDesc.contains("全采集") -> { meat += totalAdd; fish += totalAdd; veg += totalAdd; creation += totalAdd }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                // 原有逻辑：使用厨师实际装备的心法盘
                val pChef = personalData?.chefs?.get(chef.chefId)
                val diskLevel = (pChef?.dlv ?: 1).coerceAtLeast(1)
                val amberIds = pChef?.ambers ?: emptyList()
                if (amberIds.isNotEmpty()) {
                    amberIds.forEach { aid ->
                        if (aid == 0) return@forEach
                        val amber = gameData.ambers.find { it.amberId == aid.toString() }
                        if (amber != null && amber.type == 2) { // 绿盘
                            val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                            // 按每个skill逐一识别类型并加成（仅处理采集点加成，不处理素材获得加成）
                            amber.skill.forEach { sid ->
                                val skillObj = gameData.skills.find { it.skillId == sid }
                                if (skillObj != null) {
                                    val sDesc = skillObj.desc
                                    
                                    // 只处理采集点加成类技能，跳过素材获得类技能
                                    if (sDesc.contains("采集获得") || sDesc.contains("食材+")) {
                                        // 这是素材获得类技能，不影响采集点，跳过
                                        return@forEach
                                    }
                                    
                                    val base = extractBonusAmount(skillObj.desc)
                                    val totalAdd = base + levelBonusEach
                                    when {
                                        sDesc.contains("肉类采集") || sDesc.contains("采集肉类") || sDesc.contains("Meat") -> meat += totalAdd
                                        sDesc.contains("水产采集") || sDesc.contains("鱼类采集") || sDesc.contains("采集鱼类") || sDesc.contains("Fish") -> fish += totalAdd
                                        sDesc.contains("蔬菜采集") || sDesc.contains("采集蔬菜") || sDesc.contains("Vegetable") -> veg += totalAdd
                                        sDesc.contains("面类采集") || sDesc.contains("采集面类") || sDesc.contains("Creation") -> creation += totalAdd
                                        sDesc.contains("全采集") -> { meat += totalAdd; fish += totalAdd; veg += totalAdd; creation += totalAdd }
                                        else -> {
                                            // 若skill无法判定类型，则尝试用amber.desc作为兜底
                                            val d = amber.desc
                                            when {
                                                d.contains("肉类") && d.contains("采集") && !d.contains("获得") -> meat += totalAdd
                                                (d.contains("水产") || d.contains("鱼类")) && d.contains("采集") && !d.contains("获得") -> fish += totalAdd
                                                d.contains("蔬菜") && d.contains("采集") && !d.contains("获得") -> veg += totalAdd
                                                d.contains("面类") && d.contains("采集") && !d.contains("获得") -> creation += totalAdd
                                                d.contains("全采集") && !d.contains("获得") -> { meat += totalAdd; fish += totalAdd; veg += totalAdd; creation += totalAdd }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        
        return CollectionStats(meat, fish, veg, creation)
    }
    
    /**
     * 计算厨师的技能加成（暴击类和加成类技能）
     */
    private fun calculateChefSkillBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        targetType: String = "",  // 目标采集类型，用于计算心法盘素材加成
        useAllUltimateTraining: Boolean = false
    ): SkillBonus {
        return calculateChefSkillBonus(chef, gameData, personalData, targetType, false, false, useAllUltimateTraining)
    }
    
    private fun calculateChefSkillBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        targetType: String = "",  // 目标采集类型，用于计算心法盘素材加成
        useSilverShoes: Boolean = false,
        useAllUltimateTraining: Boolean = false
    ): SkillBonus {
        return calculateChefSkillBonus(chef, gameData, personalData, targetType, useSilverShoes, false, useAllUltimateTraining)
    }
    
    private fun calculateChefSkillBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        targetType: String = "",  // 目标采集类型，用于计算心法盘素材加成
        useSilverShoes: Boolean = false,
        useMaxLevelAmber: Boolean = false,
        useAllUltimateTraining: Boolean = false  // 全修炼开关
    ): SkillBonus {
        // 分别计算厨师技能和厨具技能的暴击数据
        var chefCritMaterial = 0
        var chefCritChance = 0
        var gainBonus = 0
        var priceBonus = 0
        var hasRareGuestSkill = false
        var hasOpeningTimeSkill = false
        
        // 解析厨师自身技能（如果有的话）
        if (chef.skill != 0) {
            val skill = gameData.skills.find { it.skillId == chef.skill }
            if (skill != null) {
                val bonus = parseSkillBonus(skill.desc)
                chefCritMaterial += bonus.critMaterialBonus
                chefCritChance += bonus.critChanceBonus
                gainBonus += bonus.gainBonus
                priceBonus += bonus.priceBonus
                hasRareGuestSkill = hasRareGuestSkill || bonus.hasRareGuestSkill
                hasOpeningTimeSkill = hasOpeningTimeSkill || bonus.hasOpeningTimeSkill
            }
        }
        
        // 解析厨师修炼技能（需要判断修炼状态）
        if (chef.hasUltimateSkill()) {
            // 判断是否应用修炼技能：全修炼开关开启 或 (厨师已拥有且已修炼)
            val shouldApplyUltimateSkills = if (useAllUltimateTraining) {
                true // 默认全修炼时，所有厨师都视为已修炼
            } else {
                // 关闭默认全修炼时，需要厨师已拥有且已修炼
                val personalChef = personalData?.chefs?.get(chef.chefId)
                personalChef?.got == true && personalChef.ult == true
            }
            
            if (shouldApplyUltimateSkills) {
                chef.getAllUltimateSkills().forEach { sid ->
                    val skill = gameData.skills.find { it.skillId == sid }
                    if (skill != null) {
                        val bonus = parseSkillBonus(skill.desc)
                        chefCritMaterial += bonus.critMaterialBonus
                        chefCritChance += bonus.critChanceBonus
                        gainBonus += bonus.gainBonus
                        priceBonus += bonus.priceBonus
                        hasRareGuestSkill = hasRareGuestSkill || bonus.hasRareGuestSkill
                        hasOpeningTimeSkill = hasOpeningTimeSkill || bonus.hasOpeningTimeSkill
                    }
                }
            }
        }
        
        // 分别计算厨具技能的暴击数据
        var equipCritMaterial = 0
        var equipCritChance = 0
        val equipId = personalData?.chefs?.get(chef.chefId)?.equip
        
        // 银布鞋逻辑：如果开启了银布鞋开关
        val finalEquipId = if (useSilverShoes) {
            if (equipId != null) {
                // 检查厨师当前装备是否为指定厨具ID
                val allowedEquipIds = listOf(1088, 76, 77, 78, 64, 841)
                if (equipId in allowedEquipIds) {
                    equipId // 使用当前装备
                } else {
                    65 // 默认使用65号厨具（银布鞋）
                }
            } else {
                65 // 没有装备时默认使用65号厨具（银布鞋）
            }
        } else {
            equipId // 使用原有逻辑
        }
        
        if (finalEquipId != null) {
            val equip = gameData.equips.find { it.equipId == finalEquipId.toString() }
            if (equip != null) {
                val hasDoublingSkill = chef.getAllUltimateSkills().any { it == 528 }
                equip.skill.forEach { skillId ->
                    val skill = gameData.skills.find { it.skillId == skillId }
                    if (skill != null) {
                        val bonus = parseSkillBonus(skill.desc)
                        if (hasDoublingSkill) {
                            // 528翻倍技能：仅厨具暴击素材翻倍，暴击率不翻倍
                            equipCritMaterial += bonus.critMaterialBonus * 2
                            equipCritChance += bonus.critChanceBonus  // 不翻倍
                            gainBonus += bonus.gainBonus * 2
                            priceBonus += bonus.priceBonus * 2
                            hasRareGuestSkill = hasRareGuestSkill || bonus.hasRareGuestSkill
                            hasOpeningTimeSkill = hasOpeningTimeSkill || bonus.hasOpeningTimeSkill
                        } else {
                            equipCritMaterial += bonus.critMaterialBonus
                            equipCritChance += bonus.critChanceBonus
                            gainBonus += bonus.gainBonus
                            priceBonus += bonus.priceBonus
                            hasRareGuestSkill = hasRareGuestSkill || bonus.hasRareGuestSkill
                            hasOpeningTimeSkill = hasOpeningTimeSkill || bonus.hasOpeningTimeSkill
                        }
                    }
                }
            }
        }
        
        // 选择暴击率最高的那组数据
        val (finalCritMaterial, finalCritChance) = if (equipCritChance > chefCritChance) {
            // 厨具暴击率更高，使用厨具数据
            Pair(equipCritMaterial, equipCritChance)
        } else if (chefCritChance > 0) {
            // 厨师暴击率更高或相等，使用厨师数据
            Pair(chefCritMaterial, chefCritChance)
        } else {
            // 都没有暴击技能
            Pair(0, 0)
        }
        
        // 解析心法盘素材加成（仅统计匹配目标类型的）
        if (targetType.isNotEmpty()) {
            val pChef = personalData?.chefs?.get(chef.chefId)
            val diskLevel = (pChef?.dlv ?: 1).coerceAtLeast(1)
            val amberIds = pChef?.ambers ?: emptyList()
            if (amberIds.isNotEmpty()) {
                amberIds.forEach { aid ->
                    if (aid == 0) return@forEach
                    val amber = gameData.ambers.find { it.amberId == aid.toString() }
                    if (amber != null && amber.type == 2) { // 绿盘
                        val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                        // 按每个skill逐一识别类型并加成
                        amber.skill.forEach { sid ->
                            val skillObj = gameData.skills.find { it.skillId == sid }
                            if (skillObj != null) {
                                val base = extractAmberMaterialBonus(skillObj.desc) // 使用心法盘专用解析方法
                                val totalAdd = base + levelBonusEach
                                val sDesc = skillObj.desc
                                
                                // 解析心法盘素材加成，只统计匹配目标类型的
                                val isMatchingType = when (targetType) {
                                    "肉" -> sDesc.contains("采集获得肉类食材") || sDesc.contains("肉类食材")
                                    "鱼" -> sDesc.contains("采集获得鱼类食材") || sDesc.contains("鱼类食材")
                                    "菜" -> sDesc.contains("采集获得菜类食材") || sDesc.contains("菜类食材")
                                    "面" -> sDesc.contains("采集获得加工类食材") || sDesc.contains("加工类食材")
                                    else -> false
                                }
                                
                                if (isMatchingType) {
                                    gainBonus += totalAdd
                                }
                            }
                        }
                    }
                }
            }
        }
        
        return SkillBonus(finalCritMaterial, finalCritChance, gainBonus, priceBonus, hasRareGuestSkill, hasOpeningTimeSkill, 0, 0)
    }
    
    /**
     * 解析单个技能的加成
     */
    private fun parseSkillBonus(skillDesc: String): SkillBonus {
        var critMaterialBonus = 0
        var critChanceBonus = 0
        var gainBonus = 0
        var priceBonus = 0
        var hasRareGuestSkill = false
        var hasOpeningTimeSkill = false
        var openingTimePenalty = 0
        var rareGuestChanceBonus = 0
        
        // 暴击类技能：支持多种格式
        val critPatterns = arrayOf(
            Regex("探索时有(\\d+)%概率额外获得(\\d+)%的?素材"),  // 忌璃格式：探索时有30%概率额外获得80%的素材
            Regex("有(\\d+)%概率额外获得(\\d+)%素材"),        // 四郎格式：有30%概率额外获得60%素材
            Regex("(\\d+)%概率额外获得(\\d+)%素材")           // 简化格式：30%概率额外获得60%素材
        )
        
        for (pattern in critPatterns) {
            val critMatch = pattern.find(skillDesc)
        if (critMatch != null) {
            critChanceBonus = critMatch.groupValues[1].toInt()
            critMaterialBonus = critMatch.groupValues[2].toInt()
                break
            }
        }
        
        // 加成类技能：全体*类素材获得+X%（这类技能影响素材获得概率，不是采集点加成，所以不计算）
        val allTypePattern = Regex("全体.*类素材获得\\+(\\d+)%")
        val allTypeMatch = allTypePattern.find(skillDesc)
        if (allTypeMatch != null) {
            // 这类技能不参与素材加成计算，因为它们影响的是素材获得概率，不是采集点加成
            // 不增加 gainBonus
        } else {
            // 素材获得加成技能：素材获得+X%（仅在不是全体*类素材获得时计算）
            val materialGainPattern = Regex("素材获得\\+(\\d+)%")
            val materialGainMatch = materialGainPattern.find(skillDesc)
            if (materialGainMatch != null) {
                gainBonus += materialGainMatch.groupValues[1].toInt()
            }
        }
        
        // 售价加成类技能：金币获得+X% 或 售价+X%
        val pricePatterns = arrayOf(
            Regex("金币获得\\+(\\d+)%"),
            Regex("售价\\+(\\d+)%")
        )
        for (pattern in pricePatterns) {
            val match = pattern.find(skillDesc)
            if (match != null) {
                priceBonus += match.groupValues[1].toInt()
            }
        }
        
        // 稀有客人技能（解析概率加成）
        val rareGuestKeywords = arrayOf(
            "稀有客人", "贵客", "传说客人", "神秘客人", 
            "满意+", "客人满意", "招待", "来访",
            "活动客人", "特殊客人", "限定客人"
        )
        for (keyword in rareGuestKeywords) {
            if (skillDesc.contains(keyword)) {
                hasRareGuestSkill = true
                // 尝试解析稀有客人出现概率加成，例如"稀有客人出现概率+30%"
                val rareGuestPattern = Regex(".*?出现概率\\+(\\d+)%")
                val rareGuestMatch = rareGuestPattern.find(skillDesc)
                if (rareGuestMatch != null) {
                    rareGuestChanceBonus = rareGuestMatch.groupValues[1].toInt()
                }
                break
            }
        }
        
        // 开业/营业时间类技能（解析减益数值）
        val openingKeywords = arrayOf(
            "开业时间", "营业时间", "营业开始", "开始营业", "开张", "营业分钟", "营业时长"
        )
        for (keyword in openingKeywords) {
            if (skillDesc.contains(keyword)) {
                hasOpeningTimeSkill = true
                // 尝试解析减益数值，例如"开业时间-10%"中的-10
                val penaltyPattern = Regex(".*?(\\-\\d+)%")
                val penaltyMatch = penaltyPattern.find(skillDesc)
                if (penaltyMatch != null) {
                    openingTimePenalty = penaltyMatch.groupValues[1].toInt()
                }
                break
            }
        }
        
        return SkillBonus(critMaterialBonus, critChanceBonus, gainBonus, priceBonus, hasRareGuestSkill, hasOpeningTimeSkill, openingTimePenalty, rareGuestChanceBonus)
    }
    
    /**
     * 解析厨具的采集加成
     */
    private fun parseEquipCollectionBonus(
        equip: Equip,
        skills: List<Skill>
    ): CollectionStats {
        var meatBonus = 0
        var fishBonus = 0
        var vegBonus = 0
        var creationBonus = 0
        
        equip.skill.forEach { skillId ->
            val skill = skills.find { it.skillId == skillId }
            if (skill != null) {
                val bonusAmount = extractBonusAmount(skill.desc)
                when {
                    skill.desc.contains("全采集") -> {
                        meatBonus += bonusAmount
                        fishBonus += bonusAmount
                        vegBonus += bonusAmount
                        creationBonus += bonusAmount
                    }
                    skill.desc.contains("肉类采集") -> meatBonus += bonusAmount
                    skill.desc.contains("水产采集") -> fishBonus += bonusAmount
                    skill.desc.contains("蔬菜采集") -> vegBonus += bonusAmount
                    skill.desc.contains("面类采集") -> creationBonus += bonusAmount
                }
            }
        }
        
        return CollectionStats(meatBonus, fishBonus, vegBonus, creationBonus)
    }
    
    /**
     * 从技能描述中提取加成数值
     * 例如："水产采集+3" -> 3
     */
    private fun extractBonusAmount(skillDesc: String): Int {
        return try {
            // 首先尝试提取采集加成
            val collectRegex = Regex("""采集\+(\d+)""")
            val collectMatch = collectRegex.find(skillDesc)
            if (collectMatch != null) {
                return collectMatch.groupValues[1].toInt()
            }
            
            // 然后尝试提取技法加成（如：炒+55, 煮+70等）
            val skillRegex = Regex("""[蒸炸炒煮切烤]\+(\d+)""")
            val skillMatch = skillRegex.find(skillDesc)
            if (skillMatch != null) {
                return skillMatch.groupValues[1].toInt()
            }
            
            // 尝试提取技法加成（如：蒸技法+10）
            val skillTechniqueRegex = Regex("""[蒸炸炒煮切烤]技法\+(\d+)""")
            val skillTechniqueMatch = skillTechniqueRegex.find(skillDesc)
            if (skillTechniqueMatch != null) {
                return skillTechniqueMatch.groupValues[1].toInt()
            }
            
            // 尝试提取全技法加成
            val allSkillRegex = Regex("""全技法\+(\d+)""")
            val allSkillMatch = allSkillRegex.find(skillDesc)
            if (allSkillMatch != null) {
                return allSkillMatch.groupValues[1].toInt()
            }
            
            0
        } catch (e: Exception) {
            0
        }
    }
    
    /**
     * 从心法盘技能描述中提取素材加成数值
     * 例如："采集获得鱼类食材+4%" -> 4
     */
    private fun extractAmberMaterialBonus(skillDesc: String): Int {
        return try {
            val regex = Regex("""采集获得.*?食材\+(\d+)%""")
            val matchResult = regex.find(skillDesc)
            matchResult?.groupValues?.get(1)?.toInt() ?: 0
        } catch (e: Exception) {
            0
        }
    }
    
    /**
     * 寻找指定类型的最佳心法盘（满级心法盘逻辑专用）
     */
    fun findBestAmberForType(gameData: GameData, targetType: String, maxLevel: Int): com.example.show_auto.data.Amber? {
        var bestAmber: com.example.show_auto.data.Amber? = null
        var maxTotalBonus = 0
        
        // 遍历所有绿色心法盘，寻找该类型的最高总加成（基础+等级加成）
        gameData.ambers.forEach { amber ->
            if (amber.type == 2) { // 绿色心法盘
                amber.skill.forEach { skillId ->
                    val skill = gameData.skills.find { it.skillId == skillId }
                    skill?.let { skillObj ->
                        val desc = skillObj.desc
                        // 只匹配素材获得加成类型的心法盘（采集获得XX食材+%）
                        val isMatchingType = when (targetType) {
                            "肉" -> desc.contains("采集获得肉类食材") && desc.contains("%")
                            "鱼" -> desc.contains("采集获得鱼类食材") && desc.contains("%")
                            "菜" -> desc.contains("采集获得菜类食材") && desc.contains("%")
                            "面" -> desc.contains("采集获得加工类食材") && desc.contains("%")
                            else -> false
                        }
                        
                        if (isMatchingType) {
                            // 解析素材加成基础值
                            val baseBonus = extractAmberMaterialBonus(desc)
                            if (baseBonus > 0) {
                                // 计算最高等级的总加成
                                val levelBonus = if (maxLevel > 1) amber.amplification * (maxLevel - 1) else 0
                                val totalBonus = baseBonus + levelBonus
                                
                                if (totalBonus > maxTotalBonus) {
                                    maxTotalBonus = totalBonus
                                    bestAmber = amber
                                }
                            }
                        }
                    }
                }
            }
        }
        
        return bestAmber
    }
    
    /**
     * 提取厨师的绿色心法盘数量
     */
    private fun extractGreenAmberCount(diskDesc: String): Int {
        if (diskDesc.isEmpty()) return 0
        
        // 解析格式如 "蓝|蓝|绿<br>最高5级" 中的绿色心法盘数量
        val beforeBr = diskDesc.split("<br>")[0]
        return beforeBr.split("|").count { it.trim() == "绿" }
    }
    
    /**
     * 计算厨师的两个最高采集点之和
     */
    private fun getTopTwoCollectionSum(chef: ChefWithStats): Int {
        val collectionValues = listOf(
            chef.stats.meat,
            chef.stats.fish,
            chef.stats.veg,
            chef.stats.creation
        )
        return collectionValues.sortedDescending().take(2).sum()
    }
    
    /**
     * 计算厨师的分离技能加成（用于显示）
     * 暴击类技能选择暴击率最高的那组数据，素材加成统计厨师技能+厨具技能+心法盘技能
     * 特殊规则：528翻倍技能只对厨具生效
     */
    fun calculateSeparatedSkillBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        targetType: String = ""  // 目标采集类型，用于筛选心法盘加成
    ): SeparatedSkillBonus {
        return calculateSeparatedSkillBonus(chef, gameData, personalData, targetType, false, false, false, false)
    }
    
    /**
     * 计算厨师的分离技能加成（用于显示）
     * 暴击类技能选择暴击率最高的那组数据，素材加成统计厨师技能+厨具技能+心法盘技能
     * 特殊规则：528翻倍技能只对厨具生效
     * @param useSilverShoes 是否使用银布鞋逻辑（菜地区专用）
     */
    fun calculateSeparatedSkillBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        targetType: String = "",  // 目标采集类型，用于筛选心法盘加成
        useSilverShoes: Boolean = false
    ): SeparatedSkillBonus {
        return calculateSeparatedSkillBonus(chef, gameData, personalData, targetType, useSilverShoes, false, false, false)
    }
    
    fun calculateSeparatedSkillBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        targetType: String = "",  // 目标采集类型，用于筛选心法盘加成
        useSilverShoes: Boolean = false,
        useMaxLevelAmber: Boolean = false,
        isJadeArea: Boolean = false,  // 是否是玉片区
        useAllUltimateTraining: Boolean = false  // 是否默认全修炼
    ): SeparatedSkillBonus {
    
        
        // 分别计算厨师技能和厨具技能的暴击数据
        var chefCritMaterial = 0
        var chefCritChance = 0
        var totalMaterialGain = 0
        
        // 1. 计算厨师自身技能（技能+修炼）的暴击数据
        if (chef.skill != 0) {
            val skill = gameData.skills.find { it.skillId == chef.skill }
            if (skill != null) {
                val bonus = parseSkillBonus(skill.desc)
                chefCritMaterial += bonus.critMaterialBonus
                chefCritChance += bonus.critChanceBonus
                totalMaterialGain += bonus.gainBonus
            }
        }
        
        // 检查是否应该应用修炼技能
        val shouldApplyUltimateSkills = if (useAllUltimateTraining) {
            true
        } else {
            val personalChef = personalData?.chefs?.get(chef.chefId)
            personalChef?.got == true && personalChef.ult == true
        }
        
        if (shouldApplyUltimateSkills && chef.hasUltimateSkill()) {
            chef.getAllUltimateSkills().forEach { sid ->
                val skill = gameData.skills.find { it.skillId == sid }
                if (skill != null) {
                    val bonus = parseSkillBonus(skill.desc)
                    chefCritMaterial += bonus.critMaterialBonus
                    chefCritChance += bonus.critChanceBonus
                    totalMaterialGain += bonus.gainBonus
                }
            }
        }
        
        // 2. 计算厨具技能的暴击数据
        var equipCritMaterial = 0
        var equipCritChance = 0
        val equipId = personalData?.chefs?.get(chef.chefId)?.equip
        
        // 银布鞋逻辑：如果开启了银布鞋开关
        val finalEquipId = if (useSilverShoes) {

            if (equipId != null) {
                // 检查厨师当前装备是否为指定厨具ID
                val allowedEquipIds = listOf(1088, 76, 77, 78, 64, 841)
                if (equipId in allowedEquipIds) {

                    equipId // 使用当前装备
                } else {

                    65 // 默认使用65号厨具（银布鞋）
                }
            } else {

                65 // 没有装备时默认使用65号厨具（银布鞋）
            }
        } else {

            equipId // 使用原有逻辑
        }
        
        if (finalEquipId != null) {
            val equip = gameData.equips.find { it.equipId == finalEquipId.toString() }
            if (equip != null) {
                // 检查厨师是否有厨具技能效果翻倍的修炼技能
                val shouldApplyUltimateSkills = if (useAllUltimateTraining) {
                    true
                } else {
                    val personalChef = personalData?.chefs?.get(chef.chefId)
                    personalChef?.got == true && personalChef.ult == true
                }
                val hasDoublingSkill = shouldApplyUltimateSkills && chef.getAllUltimateSkills().any { it == 528 }
                equip.skill.forEach { skillId ->
                    val skill = gameData.skills.find { it.skillId == skillId }
                    if (skill != null) {
                        val bonus = parseSkillBonus(skill.desc)
                        
                        if (hasDoublingSkill) {
                            // 翻倍技能：仅厨具暴击素材翻倍，暴击率不翻倍，素材加成翻倍
                            equipCritMaterial += bonus.critMaterialBonus * 2
                            equipCritChance += bonus.critChanceBonus  // 不翻倍
                            totalMaterialGain += bonus.gainBonus * 2
                        } else {
                            // 普通技能：全部不翻倍
                            equipCritMaterial += bonus.critMaterialBonus
                            equipCritChance += bonus.critChanceBonus
                            totalMaterialGain += bonus.gainBonus
                        }
                    }
                }
            }
            
        } else {

        }
        
        // 3. 选择暴击率最高的那组数据
        val (finalCritMaterial, finalCritChance) = if (equipCritChance > chefCritChance) {
            // 厨具暴击率更高，使用厨具数据
            Pair(equipCritMaterial, equipCritChance)
        } else if (chefCritChance > 0) {
            // 厨师暴击率更高或相等，使用厨师数据
            Pair(chefCritMaterial, chefCritChance)
        } else {
            // 都没有暴击技能
            Pair(0, 0)
        }
        
        // 4. 计算心法盘素材加成（仅统计匹配目标类型的）
        if (targetType.isNotEmpty()) {
            if (useMaxLevelAmber) {
                if (isJadeArea) {
                    // 玉片区特殊逻辑：满级心法盘时，心法盘槽位用于采集点加成，不应该有素材加成
    
                    // 不添加任何素材加成
                } else {
                    // 非玉片区：满级心法盘逻辑：根据厨师星级和地区类型计算理论最大心法盘加成

                    
                    // 根据厨师星级确定心法盘最高等级
                    val maxLevel = when (chef.rarity) {
                        5 -> 5    // 5星厨师：5级
                        4 -> 4    // 4星厨师：4级
                        else -> 3 // 3星及以下：3级
                    }
                    
                    // 获取厨师diskDesc中的绿色心法盘数量
                    val greenAmberCount = extractGreenAmberCount(chef.diskDesc)

                    
                    if (greenAmberCount > 0) {
                        // 找到该类型的最佳心法盘
                        val bestAmber = findBestAmberForType(gameData, targetType, maxLevel)
                        
                        if (bestAmber != null) {
                            // 计算单个心法盘的总加成：基础值 + (等级-1) * amplification
                            bestAmber.skill.forEach { skillId ->
                                val skill = gameData.skills.find { it.skillId == skillId }
                                if (skill != null) {
                                    val materialBonus = extractAmberMaterialBonus(skill.desc)
                                    if (materialBonus > 0) {
                                        val levelBonusEach = if (maxLevel > 1) bestAmber.amplification * (maxLevel - 1) else 0
                                        val singleAmberBonus = materialBonus + levelBonusEach
                                        val totalAmberBonus = singleAmberBonus * greenAmberCount
                                        totalMaterialGain += totalAmberBonus
                
                                        return@forEach // 只计算第一个匹配的技能
                                    }
                                }
                            }
                        } else {
    
                        }
                    } else {

                    }
                }
            } else {
                // 原有逻辑：使用厨师实际装备的心法盘和等级
    
                val pChef = personalData?.chefs?.get(chef.chefId)
                val diskLevel = (pChef?.dlv ?: 1).coerceAtLeast(1)
                val amberIds = pChef?.ambers ?: emptyList()
                if (amberIds.isNotEmpty()) {
                    amberIds.forEach { aid ->
                        if (aid == 0) return@forEach
                        val amber = gameData.ambers.find { it.amberId == aid.toString() }
                        if (amber != null && amber.type == 2) { // 绿盘
                            val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                            // 按每个skill逐一识别类型并加成（仅处理采集点加成，不处理素材获得加成）
                            amber.skill.forEach { sid ->
                                val skillObj = gameData.skills.find { it.skillId == sid }
                                if (skillObj != null) {
                                    val base = extractAmberMaterialBonus(skillObj.desc) // 使用心法盘专用解析方法
                                    val totalAdd = base + levelBonusEach
                                    val sDesc = skillObj.desc
                                    
                                    // 解析心法盘素材加成，只统计匹配目标类型的
                                    val isMatchingType = when (targetType) {
                                        "肉" -> sDesc.contains("采集获得肉类食材") || sDesc.contains("肉类食材")
                                        "鱼" -> sDesc.contains("采集获得鱼类食材") || sDesc.contains("鱼类食材")
                                        "菜" -> sDesc.contains("采集获得菜类食材") || sDesc.contains("菜类食材")
                                        "面" -> sDesc.contains("采集获得加工类食材") || sDesc.contains("加工类食材")
                                        else -> false
                                    }
                                    
                                    if (isMatchingType) {
                                        totalMaterialGain += totalAdd
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        
        return SeparatedSkillBonus(finalCritMaterial, finalCritChance, totalMaterialGain)
    }

/**
 * 菜地区域配置项（从 ComprehensiveQueryPage 移动到这里）
 */
data class VegAreaItem(
    val name: String,            // 采集点名称
    val type: String,            // 采集类型: "菜","肉","面","鱼"
    val defaultCapacity: Int,    // 默认采集点数量
    val currentCapacity: Int,    // 当前采集点数量
    val defaultPeople: Int = 3,  // 默认人数
    val currentPeople: Int = 3   // 当前人数
)

/**
 * 实验室区域配置项
 */
data class LabItem(
    val name: String,            // 采集点名称
    val currentPeople: Int,      // 当前人数
    val currentCapacity: Int     // 当前采集点数量
)

/**
 * 玉片区域配置项
 */
data class JadeAreaItem(
    val name: String,            // 采集点名称
    val type1: String,           // 第一种采集类型: "肉","鱼","菜","面"
    val type2: String,           // 第二种采集类型: "肉","鱼","菜","面"
    val defaultCapacity: Int,    // 默认采集点数量
    val currentCapacity: Int,    // 当前采集点数量
    val defaultPeople: Int = 3,  // 默认人数
    val currentPeople: Int = 3   // 当前人数
) {
    /**
     * 获取该地区需要的采集类型列表
     */
    fun getRequiredTypes(): List<String> = listOf(type1, type2)
    
    /**
     * 计算双类型采集点的总和
     */
    fun calculateTotalCapacity(chef: ChefWithStats): Int {
        return chef.getCollectionValue(type1) + chef.getCollectionValue(type2)
    }
}

/**
 * 玉片区采集结果数据类
 */
data class JadeAreaResult(
    val chefName: String,           // 厨师名称
    val rarity: Int,                // 厨师星级
    val timeEfficiency: Int,        // 时间效率（秒）
    val owned: Boolean,             // 是否已拥有
    val area: String,               // 所属区域
    val collectionStats: CollectionStats,  // 采集点统计
    val type1: String,              // 第一种采集类型
    val type2: String,              // 第二种采集类型
    val totalCapacity: Int          // 两种类型的采集点总和
)

/**
 * 计算玉片区采集编队结果
 * @param gameData 游戏数据
 * @param personalData 个人数据
 * @param jadeEnabled 是否启用玉片区
 * @param jadeAreaConfigs 玉片区配置列表
 * @return 玉片区采集结果列表
 */
fun calculateJadeAreaResults(
    gameData: GameData,
    personalData: PersonalData?,
    jadeEnabled: Boolean,
    jadeAreaConfigs: List<JadeAreaItem> = emptyList(),
    useSilverShoes: Boolean = false,
    useMaxLevelAmber: Boolean = false,
    useAllUltimateTraining: Boolean = false,
    useAllChefs: Boolean = false
): List<JadeAreaResult> {
    
    
    if (!jadeEnabled) {

        return emptyList()
    }
    
    // 筛选厨师：根据useAllChefs参数决定是否使用所有厨师
    val ownedChefs = if (useAllChefs) {
        // 使用所有厨师
        gameData.chefs
    } else if (personalData != null) {
        // 只使用已拥有的厨师
        val filtered = gameData.chefs.filter { chef ->
            personalData.chefs[chef.chefId]?.got == true
        }
        filtered
    } else {
        // 没有个人数据时，显示所有厨师作为示例
        val allChefs = gameData.chefs.take(10) // 限制显示数量
        allChefs
    }
    
    // 计算所有厨师的最终采集点和技能加成
    
    val chefsWithStats = ownedChefs.map { chef ->
        val stats = calculateChefCollectionStats(chef, gameData, personalData, useSilverShoes, useMaxLevelAmber, "", true, useAllUltimateTraining)
        val skillBonus = calculateChefSkillBonus(chef, gameData, personalData, "", useSilverShoes, useMaxLevelAmber, useAllUltimateTraining)
        // 修炼状态：默认全修炼开启时为true，否则检查厨师是否已拥有且已修炼
        val isUltimateTraining = if (useAllUltimateTraining) {
            true
        } else {
            val personalChef = personalData?.chefs?.get(chef.chefId)
            personalChef?.got == true && personalChef.ult == true
        }
        
        ChefWithStats(chef, stats, skillBonus, isUltimateTraining)
    }
    
    
    // 智能分配厨师到各个地区
    
    val allocation = allocateChefsByJadeArea(chefsWithStats, jadeAreaConfigs, gameData, personalData, useSilverShoes, useMaxLevelAmber, useAllUltimateTraining)
    
    
    // 转换为JadeAreaResult格式，按地区顺序返回
    val results = allocation.flatMap { (areaName, chefs, areaConfig) ->

        chefs.map { chefWithStats ->
            val totalCapacity = areaConfig.calculateTotalCapacity(chefWithStats)
            JadeAreaResult(
                chefName = chefWithStats.chef.name,
                rarity = chefWithStats.chef.rarity,
                timeEfficiency = 0, // 不再使用时间效率排序
                owned = personalData?.chefs?.get(chefWithStats.chef.chefId)?.got ?: false,
                area = areaName,
                collectionStats = chefWithStats.stats,
                type1 = areaConfig.type1,
                type2 = areaConfig.type2,
                totalCapacity = totalCapacity
            )
        }
    }
    
    return results
}

/**
 * 智能分配厨师到玉片区各个地区
 */
private fun allocateChefsByJadeArea(
    chefsWithStats: List<ChefWithStats>,
    jadeAreaConfigs: List<JadeAreaItem>,
    gameData: GameData,
    personalData: PersonalData?,
    useSilverShoes: Boolean = false,
    useMaxLevelAmber: Boolean = false,
    useAllUltimateTraining: Boolean = false
): List<Triple<String, List<ChefWithStats>, JadeAreaItem>> {
    
    
    val allocation = mutableListOf<Triple<String, List<ChefWithStats>, JadeAreaItem>>()
    val usedChefs = mutableSetOf<String>() // 记录已使用的厨师ID
    
    // 注意：不在此处清空insufficientAreas，由调用方统一管理
    
    // 1. 开始分配时先查看所有筛选过后的厨师的修炼技能中，有没有全场加成类技能
    val globalBonusChefs = findGlobalBonusChefs(chefsWithStats, gameData)
    
    globalBonusChefs.forEach { chef ->

    }
    
    // 过滤掉人数为0的地区，并按照配置顺序处理（严格遵循配置页顺序）
    val activeAreas = jadeAreaConfigs.filter { it.currentPeople > 0 }
    
    activeAreas.forEach { area ->

    }
    
    for (area in activeAreas) {

        
        // 筛选适合该地区的厨师（未使用且不是特殊保护厨师，开业时间减益不超过-10%，稀有客人概率加成不超过40%）
        val availableChefs = chefsWithStats.filter { c ->
            val notUsed = !usedChefs.contains(c.chef.chefId)
            val rareGuestOk = c.skillBonus.rareGuestChanceBonus <= 40 // 稀有客人出现概率加成不超过40%
            val openingTimeOk = c.skillBonus.openingTimePenalty >= -10 // 开业时间减益不超过-10%
            val ok = notUsed && rareGuestOk && openingTimeOk
            ok
        }

        
        // 按分配策略排序厨师（考虑双类型采集点）
        val sortedChefs = sortChefsByJadeAllocationStrategy(availableChefs, area, gameData, personalData)

        
        // 使用智能分配算法
        val allocatedChefs = allocateChefsByJadeBalance(
            sortedChefs, 
            area.currentPeople, 
            area.currentCapacity, 
            area,
            globalBonusChefs,
            gameData,
            jadeAreaConfigs
        )

        // 重新计算厨师采集点，根据绿色心法盘数量为对应数量的类型应用满级心法盘加成
        val recalculatedChefs = if (useMaxLevelAmber) {
            println("玉片区 ${area.name} 开启满级心法盘计算")
            allocatedChefs.map { chefWithStats ->
                // 获取厨师的绿色心法盘数量
                val greenAmberCount = extractGreenAmberCount(chefWithStats.chef.diskDesc)
                val areaTypes = listOf(area.type1, area.type2)
                
                println("厨师 ${chefWithStats.chef.name}:")
                println("  原始采集点: 肉=${chefWithStats.stats.meat}, 鱼=${chefWithStats.stats.fish}, 菜=${chefWithStats.stats.veg}, 面=${chefWithStats.stats.creation}")
                println("  绿色心法盘数量: $greenAmberCount")
                println("  地区类型: ${area.type1} + ${area.type2}")
                
                // 根据心法盘数量为地区第一个类型计算满级心法盘加成
                // 如果有多个绿色心法盘，都用于第一个类型的加成
                var newStats = chefWithStats.stats
                if (greenAmberCount > 0) {
                    // 为第一个类型计算满级心法盘加成，使用所有绿色心法盘
                val primaryType = area.type1
                    val bonus = calculateJadeMaxLevelAmberBonusForType(chefWithStats.chef, gameData, primaryType, greenAmberCount)
                    println("  ${primaryType}类型满级心法盘加成: +$bonus (使用${greenAmberCount}个绿色心法盘)")
                    
                    newStats = when (primaryType) {
                        "肉" -> newStats.copy(meat = newStats.meat + bonus)
                        "鱼" -> newStats.copy(fish = newStats.fish + bonus)
                        "菜" -> newStats.copy(veg = newStats.veg + bonus)
                        "面" -> newStats.copy(creation = newStats.creation + bonus)
                        else -> newStats
                    }
                } else {
                    println("  没有绿色心法盘，无法获得满级心法盘加成")
                }
                
                println("  最终采集点: 肉=${newStats.meat}, 鱼=${newStats.fish}, 菜=${newStats.veg}, 面=${newStats.creation}")
                println("  总采集能力: ${area.calculateTotalCapacity(ChefWithStats(chefWithStats.chef, newStats, chefWithStats.skillBonus, chefWithStats.isUltimateTraining))}")
                
                chefWithStats.copy(stats = newStats)
            }
        } else {
            allocatedChefs
        }
        
        // 应用全场采集点加成
        val enhancedChefs = applyGlobalCollectionBonusToJadeArea(
            recalculatedChefs, 
            gameData, 
            personalData, 
            useAllUltimateTraining
        )
        
        // 检查是否满足采集点要求（双类型总和，使用加成后的数值）
        val totalCapacity = enhancedChefs.sumOf { area.calculateTotalCapacity(it) }
        if (totalCapacity < area.currentCapacity && enhancedChefs.size == area.currentPeople) {
            // 无法满足采集点要求，记录该地区
            insufficientAreas.add("${area.name}(需要${area.currentCapacity}采集点，实际${totalCapacity})")
        }
        
        // 记录已使用的厨师
        enhancedChefs.forEach { chef ->
            usedChefs.add(chef.chef.chefId)
        }
        
        allocation.add(Triple(area.name, enhancedChefs, area))
    }
    
    return allocation
}

/**
 * 按玉片区分配策略排序厨师
 * 优先级：团队加成技能 > 专长匹配 > 修炼状态 > 素材获取技能优先级 > 双类型采集点高
 */
private fun sortChefsByJadeAllocationStrategy(
    chefs: List<ChefWithStats>,
    area: JadeAreaItem,
    gameData: GameData,
    personalData: PersonalData?
): List<ChefWithStats> {
    val base = compareBy<ChefWithStats> { chef -> if (chef.isProtectedChef()) 1 else 0 }
    
    // 为当前目标类型重新计算技能加成（包含心法盘加成）
    val chefsWithTargetSkills = chefs.map { chefWithStats ->
        // 玉片区需要计算两种类型的技能加成
        val type1SkillBonus = calculateChefSkillBonus(
            chefWithStats.chef, gameData, personalData, area.type1
        )
        val type2SkillBonus = calculateChefSkillBonus(
            chefWithStats.chef, gameData, personalData, area.type2
        )
        // 合并两种类型的技能加成
        val combinedSkillBonus = SkillBonus(
            critMaterialBonus = type1SkillBonus.critMaterialBonus + type2SkillBonus.critMaterialBonus,
            critChanceBonus = type1SkillBonus.critChanceBonus + type2SkillBonus.critChanceBonus,
            gainBonus = type1SkillBonus.gainBonus + type2SkillBonus.gainBonus,
            priceBonus = type1SkillBonus.priceBonus + type2SkillBonus.priceBonus,
            hasRareGuestSkill = type1SkillBonus.hasRareGuestSkill || type2SkillBonus.hasRareGuestSkill,
            hasOpeningTimeSkill = type1SkillBonus.hasOpeningTimeSkill || type2SkillBonus.hasOpeningTimeSkill,
            openingTimePenalty = 0,
            rareGuestChanceBonus = 0
        )
        chefWithStats.copy(skillBonus = combinedSkillBonus)
    }
    
    // 简化排序逻辑，只按双类型采集点总和排序
    return chefsWithTargetSkills.sortedByDescending { chef -> 
        area.calculateTotalCapacity(chef)
    }
}

/**
 * 查找全场加成类厨师
 */
private fun findGlobalBonusChefs(
    chefsWithStats: List<ChefWithStats>,
    gameData: GameData
): List<ChefWithStats> {
    return chefsWithStats.filter { chefWithStats ->
        chefWithStats.chef.hasUltimateSkill() && hasGlobalBonusSkill(chefWithStats.chef, gameData)
    }
}

/**
 * 检查厨师是否有全场加成技能
 * 匹配格式：场上所有厨师*和*各+*
 */
private fun hasGlobalBonusSkill(chef: Chef, gameData: GameData): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    for (skillId in chef.getAllUltimateSkills()) {
        val skill = gameData.skills.find { it.skillId == skillId }
        if (skill != null) {
            val desc = skill.desc
            // 匹配多类型采集点加成：场上所有厨师*和*各+*
            val multiTypePattern = Regex("场上所有厨师.*和.*各\\+\\d+")
            if (multiTypePattern.find(desc) != null) {
                return true
            }
        }
    }
    return false
}

/**
 * 获取厨师的全场加成技能描述
 */
private fun getGlobalBonusSkillDescription(chef: Chef, gameData: GameData): String {
    if (!chef.hasUltimateSkill()) return "无"
    
    val skillDescriptions = mutableListOf<String>()
    for (skillId in chef.getAllUltimateSkills()) {
        val skill = gameData.skills.find { it.skillId == skillId }
        if (skill != null) {
            val desc = skill.desc
            // 匹配多类型采集点加成：场上所有厨师*和*各+*
            val multiTypePattern = Regex("场上所有厨师.*和.*各\\+\\d+")
            if (multiTypePattern.find(desc) != null) {
                skillDescriptions.add(desc)
            }
        }
    }
    return skillDescriptions.joinToString(", ")
}

/**
 * 查找匹配地区需求的全场加成厨师
 * 只匹配多类型采集点加成：场上所有厨师*和*各+*
 */
private fun findMatchingGlobalBonusChefs(
    globalBonusChefs: List<ChefWithStats>,
    area: JadeAreaItem,
    availableChefs: List<ChefWithStats>,
    gameData: GameData
): List<ChefWithStats> {
    val requiredTypes = area.getRequiredTypes()
    val matchingChefs = mutableListOf<ChefWithStats>()
    
    // 只考虑可用的厨师
    val availableGlobalBonusChefs = globalBonusChefs.filter { it in availableChefs }
    
    // 查找多类型采集点加成厨师
    val multiTypeChefs = availableGlobalBonusChefs.filter { chef ->
        hasMultiTypeGlobalBonusSkill(chef.chef, requiredTypes, gameData)
    }
    
    if (multiTypeChefs.isNotEmpty()) {

        matchingChefs.addAll(multiTypeChefs)
    }
    
    return matchingChefs
}

/**
 * 计算每个厨师在所有玉片地区的采集点组合，找出最佳匹配
 */
private fun calculateChefBestAreaMatches(
    chefs: List<ChefWithStats>,
    jadeAreaConfigs: List<JadeAreaItem>
): Map<ChefWithStats, Pair<JadeAreaItem, Int>> {
    val chefBestMatches = mutableMapOf<ChefWithStats, Pair<JadeAreaItem, Int>>()
    
    for (chef in chefs) {
        var bestArea: JadeAreaItem? = null
        var bestCapacity = 0
        
        for (area in jadeAreaConfigs) {
            val capacity = area.calculateTotalCapacity(chef)
            if (capacity > bestCapacity) {
                bestCapacity = capacity
                bestArea = area
            }
        }
        
        if (bestArea != null) {
            chefBestMatches[chef] = bestArea to bestCapacity
        }
    }
    
    return chefBestMatches
}

/**
 * 为当前地区找出最适合的厨师，考虑最佳地区匹配
 * 如果厨师在当前地区不是最佳匹配，且在其他地区有更好的匹配，则优先考虑其他厨师
 */
private fun findBestChefForCurrentArea(
    availableChefs: List<ChefWithStats>,
    currentArea: JadeAreaItem,
    jadeAreaConfigs: List<JadeAreaItem>
): ChefWithStats? {
    if (availableChefs.isEmpty()) return null
    
    // 计算每个厨师在所有地区的采集点组合
    val chefBestMatches = calculateChefBestAreaMatches(availableChefs, jadeAreaConfigs)
    
    // 找出在当前地区采集点最高的厨师
    val bestChefForCurrentArea = availableChefs.maxByOrNull { chef ->
        currentArea.calculateTotalCapacity(chef)
    }
    
    if (bestChefForCurrentArea == null) return null
    
    // 检查该厨师是否在当前地区有最佳匹配
    val chefBestMatch = chefBestMatches[bestChefForCurrentArea]
    if (chefBestMatch != null && chefBestMatch.first == currentArea) {
        // 该厨师在当前地区就是最佳匹配，直接返回

        return bestChefForCurrentArea
    }
    
    // 该厨师在当前地区不是最佳匹配，检查是否有其他厨师在当前地区是更好的选择
    val alternativeChefs = availableChefs.filter { chef ->
        val chefBestMatch = chefBestMatches[chef]
        chefBestMatch != null && chefBestMatch.first == currentArea
    }
    
    if (alternativeChefs.isNotEmpty()) {
        // 有厨师在当前地区是最佳匹配，选择其中采集点最高的
        val bestAlternative = alternativeChefs.maxByOrNull { chef ->
            currentArea.calculateTotalCapacity(chef)
        }
        if (bestAlternative != null) {
    
            return bestAlternative
        }
    }
    
    // 没有找到更好的选择，返回当前地区采集点最高的厨师
    
    return bestChefForCurrentArea
}

/**
 * 检查厨师是否有匹配地区的多类型全场加成技能
 */
private fun hasMultiTypeGlobalBonusSkill(chef: Chef, requiredTypes: List<String>, gameData: GameData): Boolean {
    if (!chef.hasUltimateSkill()) return false
    
    for (skillId in chef.getAllUltimateSkills()) {
        val skill = gameData.skills.find { it.skillId == skillId }
        if (skill != null) {
            val desc = skill.desc
            // 匹配多类型采集点加成：场上所有厨师*和*各+*
            val multiTypePattern = Regex("场上所有厨师(.*)和(.*)各\\+(\\d+)")
            val match = multiTypePattern.find(desc)
            if (match != null) {
                val type1 = match.groupValues[1].trim()
                val type2 = match.groupValues[2].trim()
                // 检查是否匹配地区需求的采集点类型
                if (requiredTypes.contains(type1) && requiredTypes.contains(type2)) {
                    return true
                }
            }
        }
    }
    return false
}



/**
 * 检查厨师是否有团队加成技能（暂时禁用）
 */
private fun hasTeamBonusSkill(chef: Chef, gameData: GameData, area: JadeAreaItem): Boolean {
    // 暂时禁用团队加成技能检测，简化查询逻辑
    return false
}

/**
 * 玉片区智能分配算法：优先分配全场加成类厨师，然后按采集点排序分配
 */
private fun allocateChefsByJadeBalance(
    sortedChefs: List<ChefWithStats>,
    neededCount: Int,
    targetCapacity: Int,
    area: JadeAreaItem,
    globalBonusChefs: List<ChefWithStats>,
    gameData: GameData,
    jadeAreaConfigs: List<JadeAreaItem>
): List<ChefWithStats> {
    
    
    if (sortedChefs.isEmpty()) {

        return emptyList()
    }
    
    val result = mutableListOf<ChefWithStats>()
    val availableChefs = sortedChefs.toMutableList()
    
    // 2. 开始按顺序对各区域分配，分配时先查看该地区的采集点类型要求
    val requiredTypes = area.getRequiredTypes()
    
    
    // 优先分配全场加成类厨师
    val matchingGlobalBonusChefs = findMatchingGlobalBonusChefs(globalBonusChefs, area, availableChefs, gameData)
    
    
    // 先分配匹配的全场加成厨师
    for (chef in matchingGlobalBonusChefs) {
        if (result.size < neededCount && availableChefs.contains(chef)) {
            result.add(chef)
            availableChefs.remove(chef)
    
        }
    }
    
    // 然后按采集点排序分配其他厨师，考虑最佳地区匹配
    val remainingChefs = availableChefs.toMutableList()
    
    while (result.size < neededCount && remainingChefs.isNotEmpty()) {
        // 找出当前地区最适合的厨师（考虑最佳地区匹配）
        val bestChefForCurrentArea = findBestChefForCurrentArea(remainingChefs, area, jadeAreaConfigs)
        
        if (bestChefForCurrentArea != null) {
            result.add(bestChefForCurrentArea)
            remainingChefs.remove(bestChefForCurrentArea)
    
        } else {
            // 如果没有找到合适的，取第一个
            val chef = remainingChefs.removeAt(0)
            // 保护：稀有客人概率加成超过40%的厨师跳过，开业时间减益超过-10%的厨师跳过
            if (chef.skillBonus.rareGuestChanceBonus > 40 || chef.skillBonus.openingTimePenalty < -10) {
        
                continue
            }
            result.add(chef)
    
        }
    }
    
    
    return result
}

/**
 * 计算厨师的全场加成数值
 * @param chef 厨师
 * @param gameData 游戏数据
 * @return 全场加成信息，包含类型和数值
 */
fun calculateGlobalBonusValues(
    chef: Chef, 
    gameData: GameData, 
    personalData: PersonalData? = null, 
    useAllUltimateTraining: Boolean = false
): GlobalBonusInfo {
    // 检查是否应该应用修炼技能
    val shouldApplyUltimateSkills = if (useAllUltimateTraining) {
        true
    } else {
        val personalChef = personalData?.chefs?.get(chef.chefId)
        personalChef?.got == true && personalChef.ult == true
    }
    
    if (!chef.hasUltimateSkill() || !shouldApplyUltimateSkills) return GlobalBonusInfo()
    
    val bonusInfo = GlobalBonusInfo()
    
    for (skillId in chef.getAllUltimateSkills()) {
        val skill = gameData.skills.find { it.skillId == skillId }
        if (skill != null) {
            val desc = skill.desc
            // 匹配多类型采集点加成：场上所有厨师*和*各+*
            val multiTypePattern = Regex("场上所有厨师(.*)和(.*)各\\+(\\d+)")
            val match = multiTypePattern.find(desc)
            if (match != null) {
                val type1 = match.groupValues[1].trim()
                val type2 = match.groupValues[2].trim()
                val bonusValue = match.groupValues[3].toIntOrNull() ?: 0
                
                when (type1) {
                    "肉" -> bonusInfo.meatBonus = bonusValue
                    "鱼" -> bonusInfo.fishBonus = bonusValue
                    "菜" -> bonusInfo.vegBonus = bonusValue
                    "面" -> bonusInfo.creationBonus = bonusValue
                }
                
                when (type2) {
                    "肉" -> bonusInfo.meatBonus = bonusValue
                    "鱼" -> bonusInfo.fishBonus = bonusValue
                    "菜" -> bonusInfo.vegBonus = bonusValue
                    "面" -> bonusInfo.creationBonus = bonusValue
                }
            }
        }
    }
    
    return bonusInfo
}

/**
 * 全场加成信息数据类
 */
data class GlobalBonusInfo(
    var meatBonus: Int = 0,
    var fishBonus: Int = 0,
    var vegBonus: Int = 0,
    var creationBonus: Int = 0
) {
    fun hasBonus(): Boolean = meatBonus > 0 || fishBonus > 0 || vegBonus > 0 || creationBonus > 0
    
    fun getBonusForType(type: String): Int = when (type) {
        "肉" -> meatBonus
        "鱼" -> fishBonus
        "菜" -> vegBonus
        "面" -> creationBonus
        else -> 0
    }
}

    /**
     * 玉片区专用：寻找指定类型的最佳采集点加成心法盘
     * 与菜地区不同，玉片区使用采集点加成类型而不是素材加成类型
     */
    fun findBestJadeAmberForType(gameData: GameData, targetType: String, maxLevel: Int): com.example.show_auto.data.Amber? {
        println("        查找最佳玉片区心法盘 - 目标类型: $targetType")
        
        val greenAmbers = gameData.ambers.filter { amber ->
            amber.type == 2 // 绿盘
        }
        println("        总绿色心法盘数量: ${greenAmbers.size}")
        
        val matchingAmbers = greenAmbers.filter { amber ->
            val hasMatchingSkill = amber.skill.any { skillId ->
                val skill = gameData.skills.find { it.skillId == skillId }
                if (skill != null) {
                    val skillDesc = skill.desc
                    // 玉片区专用：查找采集点加成技能，不是素材获得加成
                    val isTargetType = when (targetType) {
                        "肉" -> skillDesc.contains("肉类采集") || skillDesc.contains("采集肉类")
                        "鱼" -> skillDesc.contains("水产采集") || skillDesc.contains("鱼类采集") || skillDesc.contains("采集鱼类")
                        "菜" -> skillDesc.contains("蔬菜采集") || skillDesc.contains("采集蔬菜")
                        "面" -> skillDesc.contains("面类采集") || skillDesc.contains("采集面类")
                        else -> false
                    }
                    val isCollectionSkill = !skillDesc.contains("获得") // 排除素材获得类技能
                    val matches = isTargetType && isCollectionSkill
                    if (matches) {
                        println("          匹配心法盘: ${amber.name}, 技能: $skillDesc")
                    }
                    matches
                } else {
                    false
                }
            }
            hasMatchingSkill
        }
        
        println("        匹配的心法盘数量: ${matchingAmbers.size}")
        
        val bestAmber = matchingAmbers.maxByOrNull { amber ->
            // 找到基础加成最高的
            val maxBonus = amber.skill.mapNotNull { skillId ->
                val skill = gameData.skills.find { it.skillId == skillId }
                if (skill != null) {
                    val bonus = extractBonusAmount(skill.desc)
                    println("          心法盘 ${amber.name} 技能加成: $bonus (${skill.desc})")
                    bonus
                } else {
                    0
                }
            }.maxOrNull() ?: 0
            maxBonus
        }
        
        println("        选择的最佳心法盘: ${bestAmber?.name ?: "无"}")
        return bestAmber
    }

    /**
     * 玉片区专用：提取心法盘采集点加成数值
     */
    private fun extractJadeAmberCollectionBonus(skillDesc: String): Int {
        // 匹配采集点加成格式，如"肉类采集+3"，"采集肉类+2"等
        val patterns = listOf(
            Regex("采集\\+(\\d+)"),
            Regex("肉类\\+(\\d+)"),
            Regex("鱼类\\+(\\d+)"),
            Regex("蔬菜\\+(\\d+)"),
            Regex("面类\\+(\\d+)")
        )
        
        for (pattern in patterns) {
            val match = pattern.find(skillDesc)
            if (match != null) {
                return match.groupValues[1].toIntOrNull() ?: 0
            }
        }
        
        return extractBonusAmount(skillDesc) // 回退到通用提取方法
    }

    /**
     * 玉片区专用：计算满级心法盘的采集点加成（指定心法盘数量）
     */
    fun calculateJadeMaxLevelAmberBonusForType(
        chef: Chef,
        gameData: GameData,
        targetType: String,
        amberCount: Int
    ): Int {
        println("    计算玉片区满级心法盘加成 - 厨师: ${chef.name}, 目标类型: $targetType, 心法盘数量: $amberCount")
        
        // 根据厨师星级确定心法盘最高等级
        val maxLevel = when (chef.rarity) {
            5 -> 5    // 5星厨师：5级
            4 -> 4    // 4星厨师：4级
            else -> 3 // 3星及以下：3级
        }
        println("      厨师星级: ${chef.rarity}星, 心法盘最高等级: $maxLevel")
        
        if (amberCount > 0) {
            // 找到该类型的最佳采集点加成心法盘
            val bestAmber = findBestJadeAmberForType(gameData, targetType, maxLevel)
            println("      找到的最佳心法盘: ${bestAmber?.name ?: "未找到"}")
            
            if (bestAmber != null) {
                println("      心法盘技能数量: ${bestAmber.skill.size}")
                // 计算单个心法盘的总采集点加成：基础值 + (等级-1) * amplification
                bestAmber.skill.forEach { skillId ->
                    val skill = gameData.skills.find { it.skillId == skillId }
                    if (skill != null) {
                        println("        技能: ${skill.desc}")
                        val collectionBonus = extractJadeAmberCollectionBonus(skill.desc)
                        println("        提取的采集点加成: $collectionBonus")
                        if (collectionBonus > 0) {
                            val levelBonusEach = if (maxLevel > 1) bestAmber.amplification * (maxLevel - 1) else 0
                            val singleAmberBonus = collectionBonus + levelBonusEach
                            val totalAmberBonus = singleAmberBonus * amberCount
                            println("        等级加成: $levelBonusEach (amplification: ${bestAmber.amplification})")
                            println("        单个心法盘总加成: $singleAmberBonus")
                            println("        总加成: $totalAmberBonus (数量: $amberCount)")
            
                            return totalAmberBonus
                        }
                    }
                }
            } else {
                println("      未找到匹配的心法盘")
            }
        } else {
            println("      没有绿色心法盘")
        }
        
        println("      最终返回加成: 0")
        return 0
    }

    /**
     * 玉片区专用：计算满级心法盘的采集点加成（兼容旧版本）
     */
    fun calculateJadeMaxLevelAmberBonus(
        chef: Chef,
        gameData: GameData,
        targetType: String
    ): Int {
        // 获取厨师的绿色心法盘数量
        val greenAmberCount = extractGreenAmberCount(chef.diskDesc)
        // 调用新版本函数
        return calculateJadeMaxLevelAmberBonusForType(chef, gameData, targetType, greenAmberCount)
    }

    // ===== 实验室区域相关 =====
    
    /**
     * 实验室区域结果数据类
     */
    data class LabAreaResult(
        val chefName: String,           // 厨师名称
        val rarity: Int,                // 厨师星级
        val owned: Boolean,             // 是否已拥有
        val area: String,               // 所属技法类型（蒸、炸、炒、煮、切、烤）
        val skillValue: Int,            // 技法值
        val isAuraChef: Boolean = false, // 是否为光环厨师
        val totalSkillValue: Int = 0    // 该地区最终总技法值（包含光环加成）
    )
    
    /**
     * 实验室区域配置项
     */
    data class LabAreaItem(
        val name: String,            // 技法名称（蒸、炸、炒、煮、切、烤）
        val currentPeople: Int = 5   // 当前人数
    )
    
    /**
     * 实验室厨师技法统计
     */
    data class ChefSkillStats(
        val steam: Int,     // 蒸技法
        val fry: Int,       // 炸技法
        val stirFry: Int,   // 炒技法
        val boil: Int,      // 煮技法
        val knife: Int,     // 切技法
        val bake: Int       // 烤技法
    ) {
        /**
         * 根据技法类型获取对应的技法值
         */
        fun getSkillValue(skillType: String): Int {
            return when (skillType) {
                "蒸" -> steam
                "炸" -> fry
                "炒" -> stirFry
                "煮" -> boil
                "切" -> knife
                "烤" -> bake
                else -> 0
            }
        }
    }
    
    /**
     * 带技法统计的厨师
     */
    data class ChefWithSkillStats(
        val chef: Chef,
        val skillStats: ChefSkillStats,
        val isAuraChef: Boolean = false,
        val auraSkillType: String = "", // 光环技法类型
        val auraBonus: Int = 0          // 光环加成值
    )
    

    
    /**
     * 检查技能是否为个人类技能（非上场类技能）
     */
    private fun isPartialSkill(skillId: Int): Boolean {
        // 上场类技能ID范围，这些技能只在厨师上场时生效
        val partialSkillRanges = listOf(
            (300..309), (320..329), (354..365), (430..431), (490..491), (677..678)
        )
        return partialSkillRanges.any { range -> skillId in range }
    }
    
    /**
     * 获取技能加成数值
     */
    private fun getSkillValue(skillId: Int): Int {
        return when (skillId) {
            // +1 技能
            330, 331, 332, 333, 334, 335, 311, 321, 322, 323, 324 -> 1
            // +2 技能
            336, 337, 338, 339, 340, 341, 325 -> 2
            // +3 技能
            342, 343, 344, 345, 346, 347 -> 3
            // +4 技能
            348, 349, 350, 351, 352, 353 -> 4
            // +5% 技能
            315, 317, 318, 319 -> 5
            // +25 技能
            497, 498, 499 -> 25
            // +45 技能
            485, 486, 487 -> 45
            // 默认值
            else -> 1
        }
    }

    /**
     * 计算实验室区域结果
     */
    fun calculateLabAreaResults(
        gameData: GameData,
        personalData: PersonalData?,
        labEnabled: Boolean,
        labAreaConfigs: List<LabAreaItem> = emptyList(),
        useLabEquip150: Boolean = false,
        useBeginnerEquip100: Boolean = false,
        useMaxLevelAmber: Boolean = false,
        useAllChefs: Boolean = false,
        excludedChefIds: Set<String> = emptySet(),
        savedCombinationChefIds: Set<String> = emptySet(),
        enabledAuraChefs: Set<String> = emptySet(),
        context: android.content.Context? = null,
        useAllUltimateTraining: Boolean = false
    ): List<LabAreaResult> {
        
        if (!labEnabled) {
            return emptyList()
        }
        
        // 筛选可用厨师
        val availableChefs = getAvailableChefs(
            gameData, personalData, useAllChefs, 
            excludedChefIds, savedCombinationChefIds
        )
        
        // 创建厨师列表（技法值将在具体分配时计算）
        val chefsWithSkillStats = availableChefs.map { chef ->
            val (isAura, auraType, auraBonus) = checkAuraChef(chef, gameData, enabledAuraChefs)
            
            ChefWithSkillStats(chef, ChefSkillStats(0, 0, 0, 0, 0, 0), isAura, auraType, auraBonus)
        }
        
        val results = mutableListOf<LabAreaResult>()
        

        
        // 为每个技法地区分配厨师
        labAreaConfigs.forEach { labConfig ->
            val areaResults = allocateChefsByLabArea(
                chefsWithSkillStats, labConfig, gameData, personalData, enabledAuraChefs,
                useLabEquip150, useBeginnerEquip100, useMaxLevelAmber, context, useAllUltimateTraining
            )
            results.addAll(areaResults)
        }
        
        return results
    }
    
    /**
     * 计算厨师的技法值统计 - 按照index.js的逻辑完整复刻
     */
    fun calculateChefSkillStats(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        useLabEquip150: Boolean,
        useBeginnerEquip100: Boolean,
        useMaxLevelAmber: Boolean,
        context: android.content.Context?,
        useAllUltimateTraining: Boolean = false,
        targetSkillType: String? = null
    ): ChefSkillStats {
        // 1. 加载个人技法数据
        val ultimateSkills = if (context != null) {
            val ultimateStorage = UltimateDataStorage(context)
            ultimateStorage.loadUltimateData()?.first ?: UltimateSkillsState()
        } else {
            UltimateSkillsState()
        }
        
        // 2. 获取厨具ID
        val equipId = when {
            useLabEquip150 -> {
                // 根据目标技法类型选择对应的150厨具
                when (targetSkillType) {
                    "炒" -> "190" // 炒
                    "蒸" -> "193" // 蒸
                    "烤" -> "199" // 烤
                    "煮" -> "202" // 煮
                    "炸" -> "205" // 炸
                    "切" -> "208" // 切
                    else -> null
                }
            }
            useBeginnerEquip100 -> {
                // 根据目标技法类型选择对应的100厨具
                when (targetSkillType) {
                    "炒" -> "4"   // 炒
                    "蒸" -> "13"  // 蒸
                    "烤" -> "1"   // 烤
                    "煮" -> "16"  // 煮
                    "炸" -> "10"  // 炸
                    "切" -> "7"   // 切
                    else -> null
                }
            }
            else -> {
                val personalChef = personalData?.chefs?.get(chef.chefId)
                personalChef?.equip?.toString()
            }
        }
        
        // 3. 获取红色心法盘ID和等级
        val (redAmberIds, redAmberLevel) = when {
            useMaxLevelAmber -> {
                // 默认满级心法盘开启时，根据厨师的diskDesc字段获取红色心法盘数量
                val diskDesc = chef.diskDesc
                
                // 解析diskDesc字段，计算红色心法盘数量
                val redAmberCount = if (diskDesc.isNotEmpty()) {
                    // 统计"红"出现的次数
                    diskDesc.count { it == '红' }
                } else {
                    0
                }
                
                if (redAmberCount > 0) {
                    // 有红色心法盘，根据厨师星级和技法类型选择对应心法盘
                    val maxLevel = when (chef.rarity) {
                        5 -> 5  // 5星-5级
                        4 -> 4  // 4星-4级
                        else -> 3  // 3星及以下-3级
                    }
                    
                    val amberId = when (targetSkillType) {
                        "炒" -> "3"
                        "蒸" -> "18"
                        "烤" -> "9"
                        "煮" -> "15"
                        "炸" -> "12"
                        "切" -> "6"
                        else -> null
            }
            
                    if (amberId != null) {
                        List(redAmberCount) { amberId } to maxLevel
                            } else {
                        emptyList<String>() to 1
                            }
                        } else {
                    // 没有红色心法盘，不传入
                    emptyList<String>() to 1
                }
            }
            else -> {
                // 使用厨师自身装备的心法盘
                val amberIds = if (personalData != null) {
                    val personalChef = personalData.chefs[chef.chefId]
                    if (personalChef != null && personalChef.ambers != null) {
                        // 获取厨师装备的红色心法盘ID
                        personalChef.ambers.filter { amberId ->
                            val amber = gameData.ambers.find { it.amberId == amberId.toString() }
                            amber?.type == 1 // 红色心法盘
                        }.map { it.toString() }
                    } else emptyList()
                } else emptyList()
                
                val level = if (personalData != null) {
                    val personalChef = personalData.chefs[chef.chefId]
                    if (personalChef != null) {
                        // 获取心法盘等级（为空或0就是默认为1）
                        if (personalChef.dlv == null || personalChef.dlv == 0) 1 else personalChef.dlv
                    } else 1
                } else 1
                
                amberIds to level
            }
        }
        
        // 4. 调用新的个人技法值计算函数
        // 修炼状态：默认全修炼开启时为true，否则检查厨师是否已拥有且已修炼
        val isUltimateTrained = if (useAllUltimateTraining) {
            true
        } else {
            val personalChef = personalData?.chefs?.get(chef.chefId)
            personalChef?.got == true && personalChef.ult == true
        }
        
        val enhancedChef = ChefSkillCalculator.calculateChefPersonalSkills(
            chef = chef,
            isUltimateTrained = isUltimateTrained,
            equipId = equipId,
            redAmberIds = redAmberIds,
            redAmberLevel = redAmberLevel,
            ultimateSkills = ultimateSkills,
            skills = gameData.skills,
            gameData = gameData,
            auraChefSkillIds = null // 实验室中不使用光环厨师技能加成
        )
        
        // 5. 返回计算结果
        return ChefSkillStats(
            steam = enhancedChef.steam,
            fry = enhancedChef.fry,
            stirFry = enhancedChef.stirfry,
            boil = enhancedChef.boil,
            knife = enhancedChef.knife,
            bake = enhancedChef.bake
        )
    }
    
    /**
     * 获取推荐厨具
     */
    private fun getRecommendedEquip(
        chef: Chef,
        equips: List<Equip>,
        useLabEquip150: Boolean,
        useBeginnerEquip100: Boolean,
        useMaxLevelAmber: Boolean
    ): Equip? {
        return when {
            useLabEquip150 -> {
                // 创建虚拟的实验室150厨具
                Equip(
                    equipId = "lab_150",
                    name = "实验室150厨具",
                    rarity = 5,
                    skill = emptyList()
                )
            }
            useBeginnerEquip100 -> {
                // 创建虚拟的新手100厨具
                Equip(
                    equipId = "beginner_100",
                    name = "新手100厨具",
                    rarity = 4,
                    skill = emptyList()
                )
            }
            else -> {
                // 返回null，表示不使用厨具或使用默认厨具逻辑
                null
            }
        }
    }
    
    /**
     * 厨具技法加成
     */
    private data class EquipSkillBonus(
        val steam: Int = 0,
        val fry: Int = 0,
        val stirFry: Int = 0,
        val boil: Int = 0,
        val knife: Int = 0,
        val bake: Int = 0
    )
    
    /**
     * 计算厨具技法加成
     */
    private fun calculateEquipBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        useLabEquip150: Boolean,
        useBeginnerEquip100: Boolean
    ): EquipSkillBonus {
        val personalChef = personalData?.chefs?.get(chef.chefId)
        
        return when {
            useLabEquip150 -> {
                // 实验室150厨具：所有技法+150
                EquipSkillBonus(150, 150, 150, 150, 150, 150)
            }
            useBeginnerEquip100 -> {
                // 新手100厨具：所有技法+100
                EquipSkillBonus(100, 100, 100, 100, 100, 100)
            }
            personalChef?.equip != null -> {
                // 使用厨师实际装备的厨具
                val equip = gameData.equips.find { it.equipId == personalChef.equip.toString() }
                if (equip != null) {
                    calculateEquipSkillBonus(equip, gameData)
                } else {
                    EquipSkillBonus()
                }
            }
            else -> EquipSkillBonus()
        }
    }
    
    /**
     * 计算厨具的技法加成
     */
    private fun calculateEquipSkillBonus(equip: Equip, gameData: GameData): EquipSkillBonus {
        var steam = 0
        var fry = 0
        var stirFry = 0
        var boil = 0
        var knife = 0
        var bake = 0
        
        equip.skill.forEach { skillId ->
            val skill = gameData.skills.find { it.skillId == skillId }
            if (skill != null) {
                val desc = skill.desc
                val bonus = extractBonusAmount(desc)
                
                when {
                    desc.contains("蒸技法") -> steam += bonus
                    desc.contains("炸技法") -> fry += bonus
                    desc.contains("炒技法") -> stirFry += bonus
                    desc.contains("煮技法") -> boil += bonus
                    desc.contains("切技法") -> knife += bonus
                    desc.contains("烤技法") -> bake += bonus
                }
            }
        }
        
        return EquipSkillBonus(steam, fry, stirFry, boil, knife, bake)
    }
    
    /**
     * 计算红色心法盘技法加成
     */
    private fun calculateRedAmberBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?,
        useMaxLevelAmber: Boolean
    ): EquipSkillBonus {
        if (useMaxLevelAmber) {
            // 使用满级红色心法盘加成
            return calculateMaxLevelRedAmberBonus(chef, gameData)
        } else {
            // 使用厨师实际装备的红色心法盘
            return calculateActualRedAmberBonus(chef, gameData, personalData)
        }
    }
    
    /**
     * 计算厨师实际装备的红色心法盘技法加成（实验室专用）
     */
    private fun calculateLabRedAmberBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?
    ): EquipSkillBonus {
        if (personalData == null) {
            return EquipSkillBonus()
        }
        
        // 1. 获取厨师个人数据
        val pChef = personalData.chefs[chef.chefId] ?: return EquipSkillBonus()
        
        // 2. 获取心法盘等级（为空或0就是默认为1）
        val diskLevel = if (pChef.dlv == null || pChef.dlv == 0) 1 else pChef.dlv
        
        // 3. 获取装备的心法盘ID列表
        val ambers = pChef.ambers ?: return EquipSkillBonus()
        

        
        // 存储每种技法类型的最高加成
        var maxSteamBonus = 0
        var maxFryBonus = 0
        var maxStirFryBonus = 0
        var maxBoilBonus = 0
        var maxKnifeBonus = 0
        var maxBakeBonus = 0
        
        // 4. 遍历每个心法盘
        ambers.forEach { aid ->
            val amber = gameData.ambers.find { it.amberId == aid.toString() }
            
            // 检查类型：amber.type == 1（红色心法盘）
            if (amber != null && amber.type == 1) {
                
                // 计算等级加成
                val levelBonusEach = amber.amplification * (diskLevel - 1)
                
                // 遍历心法盘的每个技能
                amber.skill.forEach { skillId ->
                    val skillObj = gameData.skills.find { it.skillId == skillId }
                    if (skillObj != null) {
                        // 获取技能描述
                        val desc = skillObj.desc
                        
                        // 提取基础加成
                        val baseBonus = extractBonusAmount(desc)
                        
                        // 计算总加成
                        val totalBonus = baseBonus + levelBonusEach
                        

                        
                        // 根据技能描述匹配对应类型并累加（使用加成值最高的心法盘）
                        when {
                            desc.contains("蒸技法") || desc.contains("蒸+") -> {
                                maxSteamBonus = maxOf(maxSteamBonus, totalBonus)
                            }
                            desc.contains("炸技法") || desc.contains("炸+") -> {
                                maxFryBonus = maxOf(maxFryBonus, totalBonus)
                            }
                            desc.contains("炒技法") || desc.contains("炒+") -> {
                                maxStirFryBonus = maxOf(maxStirFryBonus, totalBonus)
                            }
                            desc.contains("煮技法") || desc.contains("煮+") -> {
                                maxBoilBonus = maxOf(maxBoilBonus, totalBonus)
                            }
                            desc.contains("切技法") || desc.contains("切+") -> {
                                maxKnifeBonus = maxOf(maxKnifeBonus, totalBonus)
                            }
                            desc.contains("烤技法") || desc.contains("烤+") -> {
                                maxBakeBonus = maxOf(maxBakeBonus, totalBonus)
                            }
                            desc.contains("全技法") -> {
                                // 全技法加成应用到所有技法类型
                                maxSteamBonus = maxOf(maxSteamBonus, totalBonus)
                                maxFryBonus = maxOf(maxFryBonus, totalBonus)
                                maxStirFryBonus = maxOf(maxStirFryBonus, totalBonus)
                                maxBoilBonus = maxOf(maxBoilBonus, totalBonus)
                                maxKnifeBonus = maxOf(maxKnifeBonus, totalBonus)
                                maxBakeBonus = maxOf(maxBakeBonus, totalBonus)
                            }
                        }
                    }
                }
            }
        }
        

        
        return EquipSkillBonus(maxSteamBonus, maxFryBonus, maxStirFryBonus, maxBoilBonus, maxKnifeBonus, maxBakeBonus)
    }
    
    /**
     * 计算满级红色心法盘加成
     */
    private fun calculateMaxLevelRedAmberBonus(
        chef: Chef,
        gameData: GameData
    ): EquipSkillBonus {
        // 根据厨师星级确定心法盘最高等级
        val maxLevel = when (chef.rarity) {
            5 -> 5
            4 -> 4
            else -> 3
        }
        
        // 获取红色心法盘数量
        val redAmberCount = extractRedAmberCount(chef.diskDesc)
        
        if (redAmberCount > 0) {
            // 为每种技法类型找到最佳红色心法盘
            val steamBonus = findBestRedAmberForSkill(gameData, "蒸", maxLevel) * redAmberCount
            val fryBonus = findBestRedAmberForSkill(gameData, "炸", maxLevel) * redAmberCount
            val stirFryBonus = findBestRedAmberForSkill(gameData, "炒", maxLevel) * redAmberCount
            val boilBonus = findBestRedAmberForSkill(gameData, "煮", maxLevel) * redAmberCount
            val knifeBonus = findBestRedAmberForSkill(gameData, "切", maxLevel) * redAmberCount
            val bakeBonus = findBestRedAmberForSkill(gameData, "烤", maxLevel) * redAmberCount
            
            return EquipSkillBonus(steamBonus, fryBonus, stirFryBonus, boilBonus, knifeBonus, bakeBonus)
        }
        
        return EquipSkillBonus()
    }
    
    /**
     * 计算实际装备的红色心法盘加成
     * 按照你提供的红色心法盘逻辑：使用加成值最高的心法盘
     */
    private fun calculateActualRedAmberBonus(
        chef: Chef,
        gameData: GameData,
        personalData: PersonalData?
    ): EquipSkillBonus {
        val personalChef = personalData?.chefs?.get(chef.chefId)
        val diskLevel = (personalChef?.dlv ?: 0).let { if (it == 0) 1 else it } // 为空或0就是默认为1
        val amberIds = personalChef?.ambers ?: emptyList()
        
        var maxSteam = 0
        var maxFry = 0
        var maxStirFry = 0
        var maxBoil = 0
        var maxKnife = 0
        var maxBake = 0
        
        // 遍历每个心法盘，找到每种技法类型的最高加成
        amberIds.forEach { aid ->
            if (aid == 0) return@forEach
            val amber = gameData.ambers.find { it.amberId == aid.toString() }
            if (amber != null && amber.type == 1) { // 红色心法盘
                val levelBonusEach = if (diskLevel > 1) amber.amplification * (diskLevel - 1) else 0
                
                // 计算这个心法盘对每种技法的加成
                var currentSteam = 0
                var currentFry = 0
                var currentStirFry = 0
                var currentBoil = 0
                var currentKnife = 0
                var currentBake = 0
                
                amber.skill.forEach { sid ->
                    val skillObj = gameData.skills.find { it.skillId == sid }
                    if (skillObj != null) {
                        val base = extractBonusAmount(skillObj.desc)
                        val totalAdd = base + levelBonusEach
                        val sDesc = skillObj.desc
                        
                        when {
                            sDesc.contains("蒸技法") -> currentSteam += totalAdd
                            sDesc.contains("炸技法") -> currentFry += totalAdd
                            sDesc.contains("炒技法") -> currentStirFry += totalAdd
                            sDesc.contains("煮技法") -> currentBoil += totalAdd
                            sDesc.contains("切技法") -> currentKnife += totalAdd
                            sDesc.contains("烤技法") -> currentBake += totalAdd
                        }
                    }
                }
                
                // 使用加成值最高的心法盘
                maxSteam = maxOf(maxSteam, currentSteam)
                maxFry = maxOf(maxFry, currentFry)
                maxStirFry = maxOf(maxStirFry, currentStirFry)
                maxBoil = maxOf(maxBoil, currentBoil)
                maxKnife = maxOf(maxKnife, currentKnife)
                maxBake = maxOf(maxBake, currentBake)
            }
        }
        
        return EquipSkillBonus(maxSteam, maxFry, maxStirFry, maxBoil, maxKnife, maxBake)
    }
    

    
    /**
     * 提取红色心法盘数量
     */
    private fun extractRedAmberCount(diskDesc: String): Int {
        val redCount = diskDesc.count { it == '红' }
        return redCount
    }
    
    /**
     * 找到指定技法类型的最佳红色心法盘加成
     */
    private fun findBestRedAmberForSkill(
        gameData: GameData,
        skillType: String,
        maxLevel: Int
    ): Int {
        val redAmbers = gameData.ambers.filter { it.type == 1 } // 红色心法盘
        
        var maxBonus = 0
        redAmbers.forEach { amber ->
            amber.skill.forEach { skillId ->
                val skill = gameData.skills.find { it.skillId == skillId }
                if (skill != null && skill.desc.contains("${skillType}技法")) {
                    val baseBonus = extractBonusAmount(skill.desc)
                    val levelBonus = if (maxLevel > 1) amber.amplification * (maxLevel - 1) else 0
                    val totalBonus = baseBonus + levelBonus
                    if (totalBonus > maxBonus) {
                        maxBonus = totalBonus
                    }
                }
            }
        }
        
        return maxBonus
    }
    
    /**
     * 检查厨师是否为光环厨师，并返回光环信息
     */
    private fun checkAuraChef(chef: Chef, gameData: GameData, enabledAuraChefs: Set<String>, preferredSkillType: String = ""): Triple<Boolean, String, Int> {
        // 直接检查厨师是否在启用的光环厨师列表中
        if (!enabledAuraChefs.contains(chef.name)) {
            return Triple(false, "", 0)
        }
        

        
        // 获取所有修炼技能的描述
        val skillDescs = chef.getAllUltimateSkills().mapNotNull { skillId ->
            gameData.skills.find { it.skillId == skillId }?.desc
        }
        val combinedDesc = skillDescs.joinToString("\n")
        
        // 检查是否包含技法加成
        fun hasSkillBonus(desc: String): Boolean {
            return desc.contains("炒+") || desc.contains("煮+") || desc.contains("切+") || 
                   desc.contains("炸+") || desc.contains("烤+") || desc.contains("蒸+") || 
                   desc.contains("全技法+")
        }
        
        // 验证确实是光环厨师（双重检查）
        val isAuraChef = (combinedDesc.contains("场上所有厨师") || combinedDesc.contains("下位上场厨师")) &&
                        (!combinedDesc.contains("售价") || hasSkillBonus(combinedDesc)) &&
                        !combinedDesc.contains("采集") &&
                        !combinedDesc.contains("菜") &&
                        !combinedDesc.contains("鱼") &&
                        !combinedDesc.contains("肉") &&
                        !combinedDesc.contains("面")
        
        if (isAuraChef) {
            
            // 确定技法类型和加成值
            val skillTypes = listOf("蒸", "炸", "炒", "煮", "切", "烤")
            
            // 如果有优先技法类型，先检查优先技法
            if (preferredSkillType.isNotEmpty() && skillTypes.contains(preferredSkillType)) {
                if (combinedDesc.contains("${preferredSkillType}技法") || combinedDesc.contains("${preferredSkillType}+")) {
                    chef.getAllUltimateSkills().forEach { skillId ->
                        val skill = gameData.skills.find { it.skillId == skillId }
                        if (skill != null && (skill.desc.contains("${preferredSkillType}技法") || skill.desc.contains("${preferredSkillType}+"))) {
                            val bonus = extractBonusAmount(skill.desc)
                            if (bonus > 0) {
                                return Triple(true, preferredSkillType, bonus)
                            }
                        }
                    }
                }
            }
            
            // 如果没有优先技法或优先技法不匹配，按原有顺序检查
            skillTypes.forEach { skillType ->
                // 跳过已经检查过的优先技法
                if (skillType == preferredSkillType) return@forEach
                
                if (combinedDesc.contains("${skillType}技法") || combinedDesc.contains("${skillType}+")) {
                    chef.getAllUltimateSkills().forEach { skillId ->
                        val skill = gameData.skills.find { it.skillId == skillId }
                        if (skill != null && (skill.desc.contains("${skillType}技法") || skill.desc.contains("${skillType}+"))) {
                            val bonus = extractBonusAmount(skill.desc)
                            if (bonus > 0) {
                                return Triple(true, skillType, bonus)
                            }
                        }
                    }
                }
            }
            
                         // 检查全技法加成
             if (combinedDesc.contains("全技法+")) {
                 chef.getAllUltimateSkills().forEach { skillId ->
                    val skill = gameData.skills.find { it.skillId == skillId }
                    if (skill != null && skill.desc.contains("全技法+")) {
                        val bonus = extractBonusAmount(skill.desc)
                        if (bonus > 0) {
                            return Triple(true, "全技法", bonus)
                        }
                    }
                }

            }
        }
        
        return Triple(false, "", 0)
    }
    
    /**
     * 获取可用厨师（排除已分配和已保存组合中的厨师）
     */
    private fun getAvailableChefs(
        gameData: GameData,
        personalData: PersonalData?,
        useAllChefs: Boolean,
        excludedChefIds: Set<String>,
        savedCombinationChefIds: Set<String>
    ): List<Chef> {
        val baseChefs = if (useAllChefs) {
            gameData.chefs
        } else {
            // 只使用已拥有的厨师
            if (personalData != null) {
                gameData.chefs.filter { chef ->
                    personalData.chefs[chef.chefId]?.got == true
                }
            } else {
                gameData.chefs.take(10) // 没有个人数据时显示前10个作为示例
            }
        }
        
        // 排除已分配和已保存组合中的厨师
        return baseChefs.filter { chef ->
            chef.chefId !in excludedChefIds && chef.chefId !in savedCombinationChefIds
        }
    }
    
    /**
     * 为单个实验室地区分配厨师
     */
    private fun allocateChefsByLabArea(
        chefsWithSkillStats: List<ChefWithSkillStats>,
        labConfig: LabAreaItem,
        gameData: GameData,
        personalData: PersonalData?,
        enabledAuraChefs: Set<String> = emptySet(),
        useLabEquip150: Boolean = false,
        useBeginnerEquip100: Boolean = false,
        useMaxLevelAmber: Boolean = false,
        context: android.content.Context? = null,
        useAllUltimateTraining: Boolean = false
    ): List<LabAreaResult> {
        val skillType = labConfig.name
        val peopleCount = labConfig.currentPeople
        
        if (peopleCount <= 0) return emptyList()
        
        println("实验室 ${skillType}技法 分配开始，需要人数: $peopleCount")
        
        // 1. 逐级递减筛选技法值合适的厨师
        val getBaseSkillValue = { chefWithStats: ChefWithSkillStats ->
            when (skillType) {
                "炒" -> chefWithStats.chef.stirfry
                "蒸" -> chefWithStats.chef.steam
                "烤" -> chefWithStats.chef.bake
                "煮" -> chefWithStats.chef.boil
                "炸" -> chefWithStats.chef.fry
                "切" -> chefWithStats.chef.knife
                else -> 0
            }
        }
        
        // 先分离出光环厨师（只选择当前技法类型和全技法的光环厨师，其他光环厨师按普通厨师处理）
        val auraChefs = chefsWithSkillStats.filter { chefWithStats ->
            val (isAura, auraType, _) = checkAuraChef(chefWithStats.chef, gameData, enabledAuraChefs, skillType)
            isAura && (auraType == skillType || auraType == "全技法")
        }
        
        val normalChefs = chefsWithSkillStats.filter { chefWithStats ->
            val (isAura, auraType, _) = checkAuraChef(chefWithStats.chef, gameData, enabledAuraChefs, skillType)
            !isAura || (isAura && auraType != skillType && auraType != "全技法")
        }
        
        println("  光环厨师数量: ${auraChefs.size}，普通厨师数量: ${normalChefs.size}")
        if (auraChefs.isNotEmpty()) {
            println("  ${skillType}技法相关的光环厨师:")
            auraChefs.forEach { chefWithStats ->
                val (_, auraType, auraBonus) = checkAuraChef(chefWithStats.chef, gameData, enabledAuraChefs, skillType)
                println("    ${chefWithStats.chef.name}: ${auraType}光环 +${auraBonus}")
            }
        }
        
        // 智能门槛：先尝试200，如果少于5个则降级到100，最后兜底到0
        var qualifiedNormalChefs: List<ChefWithSkillStats> = emptyList()
        var usedThreshold = 0
        
        // 第一档：基础技法值 >= 200
        val highSkillChefs = normalChefs.filter { chefWithStats ->
            getBaseSkillValue(chefWithStats) >= 200
        }
        
        if (highSkillChefs.size >= 5) {
            // 如果200门槛找到5个或以上厨师，使用这个门槛
            qualifiedNormalChefs = highSkillChefs
            usedThreshold = 200
            println("  使用技法值门槛: >= 200，找到普通厨师 ${highSkillChefs.size} 个（需要 $peopleCount 个）")
        } else {
            // 第二档：基础技法值 >= 100
            val mediumSkillChefs = normalChefs.filter { chefWithStats ->
                getBaseSkillValue(chefWithStats) >= 100
            }
            
            if (mediumSkillChefs.size >= 5) {
                qualifiedNormalChefs = mediumSkillChefs
                usedThreshold = 100
                println("  技法值门槛200找到普通厨师${highSkillChefs.size}个(<5)，降级到100，找到普通厨师 ${mediumSkillChefs.size} 个（需要 $peopleCount 个）")
            } else {
                // 第三档：包含所有普通厨师（兜底）
                qualifiedNormalChefs = normalChefs
                usedThreshold = 0
                println("  技法值门槛100找到普通厨师${mediumSkillChefs.size}个(<5)，使用所有普通厨师 ${normalChefs.size} 个（需要 $peopleCount 个）")
            }
        }
        
        // 合并光环厨师和符合条件的普通厨师
        val qualifiedChefs = if (qualifiedNormalChefs.isEmpty() && auraChefs.isEmpty()) {
            // 如果没有找到任何厨师，使用所有厨师
            chefsWithSkillStats.also {
                println("  没有找到技法值大于0的普通厨师且无光环厨师，使用所有厨师: ${it.size} 个")
            }
        } else {
            (auraChefs + qualifiedNormalChefs).also {
                println("  最终候选厨师: 光环厨师 ${auraChefs.size} 个 + 普通厨师 ${qualifiedNormalChefs.size} 个 = 总计 ${it.size} 个")
            }
        }
        
        // 2. 先对所有候选厨师计算最终技法值（包含厨具、技能等加成）
        val chefsWithFinalSkillStats = qualifiedChefs.map { chefWithStats ->
            // 重新计算技法值，传入目标技法类型
            val updatedSkillStats = calculateChefSkillStats(
                chefWithStats.chef, gameData, personalData,
                useLabEquip150, useBeginnerEquip100, useMaxLevelAmber,
                context, useAllUltimateTraining, skillType
            )
            
            // 重新计算光环信息，优先选择当前地区技法类型
            val (isAura, auraType, auraBonus) = checkAuraChef(chefWithStats.chef, gameData, enabledAuraChefs, skillType)
            
            chefWithStats.copy(
                skillStats = updatedSkillStats,
                isAuraChef = isAura,
                auraSkillType = auraType,
                auraBonus = auraBonus
            )
        }
        
        // 3. 按最终技法值（包含厨具加成）排序所有厨师
        val allChefsWithUpdatedData = chefsWithFinalSkillStats.sortedByDescending { chefWithStats ->
            chefWithStats.skillStats.getSkillValue(skillType)
        }
        
        // 分别统计普通厨师和光环厨师数量
        val normalChefCount = allChefsWithUpdatedData.count { !it.isAuraChef }
        val auraChefCount = allChefsWithUpdatedData.count { it.isAuraChef }
        println("  符合条件的厨师数量: 普通厨师 ${normalChefCount} 个，光环厨师 ${auraChefCount} 个，总计 ${allChefsWithUpdatedData.size} 个")
        
        // 打印所有符合条件厨师的技法值
        println("  ${skillType}技法厨师技法值:")
        allChefsWithUpdatedData.forEach { chefWithStats ->
            val chef = chefWithStats.chef
            val skillValue = chefWithStats.skillStats.getSkillValue(skillType)
            val isAura = if (chefWithStats.isAuraChef) " [光环:${chefWithStats.auraSkillType}+${chefWithStats.auraBonus}]" else ""
            println("    ${chef.name}: ${skillValue}$isAura")
        }
        
        // 4. 按照总贡献值重新排序所有厨师（普通厨师：最终技法值，光环厨师：技法值 + 光环值 * 人数配置）
        val sortedChefs = allChefsWithUpdatedData.sortedByDescending { chefWithStats ->
            val baseSkillValue = chefWithStats.skillStats.getSkillValue(skillType)
            
            if (chefWithStats.isAuraChef && (chefWithStats.auraSkillType == skillType || chefWithStats.auraSkillType == "全技法")) {
                // 光环厨师：基础技法值 + 光环加成 * 相应乘数
                val chef = chefWithStats.chef
                val skillDescs = chef.getAllUltimateSkills().mapNotNull { skillId ->
                    gameData.skills.find { it.skillId == skillId }?.desc
                }
                val combinedDesc = skillDescs.joinToString("\n")
                
                // 判断光环技能类型
                val isAllChefs = combinedDesc.contains("场上所有厨师")
                val isSingleChef = combinedDesc.contains("下位上场厨师")
                
                val auraMultiplier = when {
                    isAllChefs -> peopleCount  // "场上所有厨师" - 乘以人数
                    isSingleChef -> 1          // "下位上场厨师" - 只X1
                    else -> peopleCount        // 默认按所有厨师处理
                }
                
                val auraContribution = chefWithStats.auraBonus * auraMultiplier
                val totalContribution = baseSkillValue + auraContribution
                
                println("    ${chefWithStats.chef.name}: 基础技法值${baseSkillValue} + 光环贡献${auraContribution}(${chefWithStats.auraBonus}×${auraMultiplier}) = 总贡献${totalContribution}")
                totalContribution
            } else {
                // 普通厨师：只考虑基础技法值
                baseSkillValue
            }
        }
        
        // 5. 分别获取普通厨师和光环厨师的前N名
        val topNormalChefs = sortedChefs.filter { !it.isAuraChef }.take(peopleCount)
        val topAuraChefs = sortedChefs.filter { chefWithStats ->
            chefWithStats.isAuraChef && (chefWithStats.auraSkillType == skillType || chefWithStats.auraSkillType == "全技法")
        }.take(peopleCount)
        
        println("  选择的普通厨师前${peopleCount}名:")
        topNormalChefs.forEachIndexed { index, chef ->
            val skillValue = chef.skillStats.getSkillValue(skillType)
            println("    ${index + 1}. ${chef.chef.name}: 技法值$skillValue")
        }
        
        println("  选择的光环厨师前${peopleCount}名:")
        topAuraChefs.forEachIndexed { index, chefWithStats ->
            val skillValue = chefWithStats.skillStats.getSkillValue(skillType)
            
            // 计算光环贡献值（与排序逻辑保持一致）
            val chef = chefWithStats.chef
            val skillDescs = chef.getAllUltimateSkills().mapNotNull { skillId ->
                gameData.skills.find { it.skillId == skillId }?.desc
            }
            val combinedDesc = skillDescs.joinToString("\n")
            
            val isAllChefs = combinedDesc.contains("场上所有厨师")
            val isSingleChef = combinedDesc.contains("下位上场厨师")
            
            val auraMultiplier = when {
                isAllChefs -> peopleCount  // "场上所有厨师" - 乘以人数
                isSingleChef -> 1          // "下位上场厨师" - 只X1
                else -> peopleCount        // 默认按所有厨师处理
            }
            
            val auraContribution = chefWithStats.auraBonus * auraMultiplier
            val totalContribution = skillValue + auraContribution
            
            println("    ${index + 1}. ${chefWithStats.chef.name}: 技法值$skillValue + 光环贡献${auraContribution}(${chefWithStats.auraBonus}×${auraMultiplier}) = 总贡献$totalContribution")
        }
        
        // 5. 生成所有可能的组合
        val allCandidates = (topNormalChefs + topAuraChefs).distinctBy { it.chef.chefId }
        val bestCombination = findBestLabCombination(
            allCandidates, skillType, peopleCount, gameData, personalData,
            useLabEquip150, useBeginnerEquip100, useMaxLevelAmber, context, useAllUltimateTraining
        )
        
        println("  最佳组合厨师: ${bestCombination.map { it.chef.name }}")
        
        // 计算并显示最佳组合的详细信息
        // 5. 对最佳组合进行详细计算输出并获取总技法值
        val totalSkillValue = if (bestCombination.isNotEmpty()) {
            println("  最佳组合详细计算:")
            val total = calculateCombinationTotalSkill(
                bestCombination, skillType, peopleCount, gameData, personalData,
                useLabEquip150, useBeginnerEquip100, useMaxLevelAmber, context, useAllUltimateTraining, true
            )
            // 存储到静态变量中供UI使用
            lastLabAreaTotalSkills[skillType] = total
            total
        } else {
            0
        }
        
        // 6. 返回结果
        val results = bestCombination.map { chefWithStats ->
            LabAreaResult(
                chefName = chefWithStats.chef.name,
                rarity = chefWithStats.chef.rarity,
                owned = personalData?.chefs?.get(chefWithStats.chef.chefId)?.got ?: false,
                area = skillType, // 直接使用技法名称，不添加"技法"后缀
                skillValue = chefWithStats.skillStats.getSkillValue(skillType),
                isAuraChef = chefWithStats.isAuraChef,
                totalSkillValue = totalSkillValue // 设置最终总技法值
            )
        }
        
        // 打印最终分配结果
        println("  ${skillType}技法最终分配:")
        results.forEach { result ->
            val auraInfo = if (result.isAuraChef) " [光环厨师]" else ""
            println("    ${result.chefName}: ${result.skillValue}$auraInfo")
        }
        
        return results
    }
    
    /**
     * 找到最佳实验室组合
     */
    private fun findBestLabCombination(
        candidates: List<ChefWithSkillStats>,
        skillType: String,
        peopleCount: Int,
        gameData: GameData,
        personalData: PersonalData?,
        useLabEquip150: Boolean,
        useBeginnerEquip100: Boolean,
        useMaxLevelAmber: Boolean,
        context: android.content.Context?,
        useAllUltimateTraining: Boolean
    ): List<ChefWithSkillStats> {
        if (candidates.size <= peopleCount) {
            return candidates
        }
        
        // 生成所有可能的组合
        val combinations = generateCombinations(candidates, peopleCount)
        
        
        // 计算每个组合的总技法值
        var bestCombination = emptyList<ChefWithSkillStats>()
        var maxTotalSkill = 0
        
        combinations.forEachIndexed { index, combination ->
            val totalSkill = calculateCombinationTotalSkill(
                combination, skillType, peopleCount, gameData, personalData,
                useLabEquip150, useBeginnerEquip100, useMaxLevelAmber, context, useAllUltimateTraining
            )
            
            // 打印每个组合的详细信息
            val chefNames = combination.map { it.chef.name }.joinToString(", ")
            val auraInfo = combination.filter { it.isAuraChef }.map { "${it.chef.name}(${it.auraSkillType}:+${it.auraBonus})" }
            val auraDesc = if (auraInfo.isNotEmpty()) " [光环: ${auraInfo.joinToString(", ")}]" else ""
            println("    组合${index + 1}: [$chefNames]$auraDesc - 总技法值: $totalSkill")
            
            
            if (totalSkill > maxTotalSkill) {
                maxTotalSkill = totalSkill
                bestCombination = combination
                println("    ↑ 新的最佳组合！")
            }
        }
        
        return bestCombination
    }
    
    /**
     * 应用单个百分比技能效果（与ChefSkillCalculator保持一致）
     * @param chef 要应用加成的厨师
     * @param skill 技能数据
     */
    private fun applyPercentageSkillEffect(chef: Chef, skill: Skill) {
        val desc = skill.desc
        
        // 排除非自身技能：全局技能和影响其他厨师的技能
        if (desc.contains("全体") || desc.contains("场上") || desc.contains("上场")) {
            return
        }
        
        // 第一步：处理绝对值加成（先执行）
        // 处理全技法绝对值加成，如"全技法+50"
        if (desc.contains("全技法") && !desc.contains("%")) {
            val absoluteValue = extractAbsoluteValueForSkillType(desc, "全技法")
            if (absoluteValue > 0) {
                chef.stirfry += absoluteValue
                chef.boil += absoluteValue
                chef.knife += absoluteValue
                chef.fry += absoluteValue
                chef.bake += absoluteValue
                chef.steam += absoluteValue
            }
        }
        
        // 处理单项技法绝对值加成
        val skillTypes = listOf("炒技法", "煮技法", "切技法", "炸技法", "烤技法", "蒸技法")
        for (skillType in skillTypes) {
            if (desc.contains(skillType) && !desc.contains("%")) {
                val absoluteValue = extractAbsoluteValueForSkillType(desc, skillType)
                if (absoluteValue > 0) {
                    when (skillType) {
                        "炒技法" -> chef.stirfry += absoluteValue
                        "煮技法" -> chef.boil += absoluteValue
                        "切技法" -> chef.knife += absoluteValue
                        "炸技法" -> chef.fry += absoluteValue
                        "烤技法" -> chef.bake += absoluteValue
                        "蒸技法" -> chef.steam += absoluteValue
                    }
                }
            }
        }
        
        // 第二步：处理百分比加成（后执行）
        // 处理全技法百分比加成，如"全技法+15%"或"自身菜谱售价+50%且全技法+15%"
        if (desc.contains("全技法") && desc.contains("%")) {
            val percentageValue = extractPercentageValueForSkillType(desc, "全技法")
            if (percentageValue > 0) {
                val multiplier = 1.0 + percentageValue / 100.0
                
                // 对所有技法应用百分比加成，结果向上取整
                chef.stirfry = kotlin.math.ceil(chef.stirfry * multiplier).toInt()
                chef.boil = kotlin.math.ceil(chef.boil * multiplier).toInt()
                chef.knife = kotlin.math.ceil(chef.knife * multiplier).toInt()
                chef.fry = kotlin.math.ceil(chef.fry * multiplier).toInt()
                chef.bake = kotlin.math.ceil(chef.bake * multiplier).toInt()
                chef.steam = kotlin.math.ceil(chef.steam * multiplier).toInt()
            }
        }
        
        // 处理单项技法百分比加成
        for (skillType in skillTypes) {
            if (desc.contains(skillType) && desc.contains("%")) {
                val percentageValue = extractPercentageValueForSkillType(desc, skillType)
                if (percentageValue > 0) {
                    val multiplier = 1.0 + percentageValue / 100.0
                    
                    when (skillType) {
                        "炒技法" -> chef.stirfry = kotlin.math.ceil(chef.stirfry * multiplier).toInt()
                        "煮技法" -> chef.boil = kotlin.math.ceil(chef.boil * multiplier).toInt()
                        "切技法" -> chef.knife = kotlin.math.ceil(chef.knife * multiplier).toInt()
                        "炸技法" -> chef.fry = kotlin.math.ceil(chef.fry * multiplier).toInt()
                        "烤技法" -> chef.bake = kotlin.math.ceil(chef.bake * multiplier).toInt()
                        "蒸技法" -> chef.steam = kotlin.math.ceil(chef.steam * multiplier).toInt()
                    }
                }
            }
        }
    }
    
    /**
     * 从技能描述中提取特定技能类型的百分比数值
     * 例如："自身菜谱售价+50%且全技法+15%" + "全技法" -> 15
     * 例如："炒技法+20%" + "炒技法" -> 20
     */
    private fun extractPercentageValueForSkillType(desc: String, skillType: String): Int {
        val regex = Regex("""${skillType}\+(\d+)%""")
        val match = regex.find(desc)
        return match?.groupValues?.get(1)?.toIntOrNull() ?: 0
    }

    /**
     * 从技能描述中提取特定技能类型的绝对值
     * 例如："全技法+50" + "全技法" -> 50
     * 例如："炒技法+20" + "炒技法" -> 20
     */
    private fun extractAbsoluteValueForSkillType(desc: String, skillType: String): Int {
        val regex = Regex("""${skillType}\+(\d+)""")
        val match = regex.find(desc)
        return match?.groupValues?.get(1)?.toIntOrNull() ?: 0
    }
    

    
    /**
     * 计算组合的总技法值（包含光环加成）
     */
    private fun calculateCombinationTotalSkill(
        combination: List<ChefWithSkillStats>,
        skillType: String,
        peopleCount: Int,
        gameData: GameData,
        personalData: PersonalData? = null,
        useLabEquip150: Boolean = false,
        useBeginnerEquip100: Boolean = false,
        useMaxLevelAmber: Boolean = false,
        context: android.content.Context? = null,
        useAllUltimateTraining: Boolean = false,
        printDetails: Boolean = false
    ): Int {
        // 直接使用已计算好的技法值，无需重新计算
        val baseTotal = combination.sumOf { it.skillStats.getSkillValue(skillType) }
        
        if (printDetails) {
            println("      基础技法值详情:")
            combination.forEach { chefWithStats ->
                val skillValue = chefWithStats.skillStats.getSkillValue(skillType)
                println("        ${chefWithStats.chef.name}: ${skillValue}")
            }
            println("      基础技法值总和: $baseTotal")
        }
        
        // 光环加成（包括该技法专门光环和全技法光环）
        val auraChefs = combination.filter { it.isAuraChef && (it.auraSkillType == skillType || it.auraSkillType == "全技法") }
        val auraTotal = auraChefs.sumOf { chefWithStats ->
            // 需要检查技能描述来确定是否乘以人数
            val chef = chefWithStats.chef
            val skillDescs = chef.getAllUltimateSkills().mapNotNull { skillId ->
                gameData.skills.find { it.skillId == skillId }?.desc
            }
            val combinedDesc = skillDescs.joinToString("\n")
            
            // 判断光环技能类型
            val isAllChefs = combinedDesc.contains("场上所有厨师")
            val isSingleChef = combinedDesc.contains("下位上场厨师")
            
            val bonus = if (isAllChefs) {
                // "场上所有厨师" - 乘以人数
                chefWithStats.auraBonus * peopleCount
            } else if (isSingleChef) {
                // "下位上场厨师" - 只对一个厨师生效，不乘以人数
                chefWithStats.auraBonus
            } else {
                // 默认按所有厨师处理
                chefWithStats.auraBonus * peopleCount
            }
            
            if (printDetails) {
                val multiplierDesc = if (isAllChefs) {
                    "场上所有厨师 × $peopleCount"
                } else if (isSingleChef) {
                    "下位上场厨师 × 1"
                } else {
                    "默认 × $peopleCount"
                }
                println("      光环加成: ${chefWithStats.chef.name}(${chefWithStats.auraSkillType}) +${chefWithStats.auraBonus} ($multiplierDesc) = +$bonus")
            }
            bonus
        }
        
        if (printDetails && auraTotal > 0) {
            println("      光环加成总和: $auraTotal")
        }
        
        val totalSkill = baseTotal + auraTotal
        
        if (printDetails) {
            println("      最终总技法值: $baseTotal + $auraTotal = $totalSkill")
        }
        
        return totalSkill
    }
    
    /**
     * 生成所有可能的组合
     */
    private fun generateCombinations(
        candidates: List<ChefWithSkillStats>,
        count: Int
    ): List<List<ChefWithSkillStats>> {
        if (count <= 0 || candidates.isEmpty()) return emptyList()
        if (count == 1) return candidates.map { listOf(it) }
        if (count >= candidates.size) return listOf(candidates)
        
        val result = mutableListOf<List<ChefWithSkillStats>>()
        
        fun backtrack(start: Int, current: MutableList<ChefWithSkillStats>) {
            if (current.size == count) {
                result.add(current.toList())
                return
            }
            
            for (i in start until candidates.size) {
                current.add(candidates[i])
                backtrack(i + 1, current)
                current.removeAt(current.size - 1)
            }
        }
        
        backtrack(0, mutableListOf())
        return result
    }
}